我需要在wordpress网站的搜索页面上添加过滤器选项。创建了带有两个选项的下拉列表。一个是“最近添加”和“上次更新”。我们需要通过选择下拉菜单来筛选课程。
我创建了下拉列表并编写了jquery,以使用ajax调用方法钩住过滤器。已创建筛选器。php文件,并在此文件中钩住pre\\u get\\u posts方法。如果我们选择下拉列表,它需要挂接该过滤器,但它不会挂接。此外,我还尝试通过ajax调用传递参数,但不起作用。请分享实现过滤器选项的想法。
HTML
<select id="filter">
<option value=\'last_updated_posts\' id=\'recently_added\'>
Last Updated
</option>
<option value="recently_added_posts" id=\'last_updated\'>
Recently Added
</option>
</select>
Custom.js
jQuery("#filter").change(function(){
var selected_option=jQuery("#filter option:selected").val();
jQuery.ajax({
type: \'POST\',
url: ajaxurl,
data: {\'action\' :selected_option },
success: function(response){alert(response);}
});
});
filter.php
<?php
add_action(\'wp_ajax_recently_added_posts\', \'recently_added_posts\');
add_action(\'wp_ajax_nopriv_recently_added_posts\', \'recently_added_posts\');
if($_POST[\'action\'] ==\'recently_added_posts\' ){
function recently_added_posts($query) {
if ($query->is_search() && !is_admin() ) {
$query->set(\'post_type\',array(\'sfwd-courses\',\'sfwd-lessons\',\'sfwd-topic\'));
$query->set(\'orderby\',array(
\'post_type\'=> \'ASC\',
\'date\' => \'DESC\')
);
return $query;
die();
}
add_filter(\'pre_get_posts\',\'recently_added_posts\');
}
}
add_action(\'wp_ajax_last_updated_posts\', \'last_updated_posts\');
add_action(\'wp_ajax_nopriv_last_updated_posts\', \'last_updated_posts\');
if($_POST[\'action\'] ==\'last_updated_posts\' ){
function last_updated_posts($query) {
if ($query->is_search() && !is_admin() ) {
$query->set(\'post_type\',array(\'sfwd-courses\',\'sfwd-lessons\',\'sfwd-topic\'));
$query->set(\'orderby\',array(
\'post_type\'=> \'ASC\',
\'modified\' => \'DESC\')
);
}
return $query;
die();
}
add_filter(\'pre_get_posts\',\'last_updated_posts\');
}
function ajaxurl_filter() {
echo \'<script type="text/javascript">
var ajaxurl = "\' . admin_url(\'admin-ajax.php\') . \'";
</script>\';
}
add_action(\'wp_head\', \'ajaxurl_filter\');
?>
提前感谢!