pre_get_posts是一个强大的文章过滤器
参考1:
function return_only_selected_category() { if ( isset($_REQUEST['s']) && isset($_REQUEST['cat']) ){ //若为搜索页面,且有cat值传入 global $wp_query; $desired_cat = $_REQUEST['cat']; //要搜索的分类 $excluded = get_categories("hide_empty=false&exclude={$desired_cat}"); //要排除的分类 $wp_query->query_vars['cat'] = "-{$excluded}"; //除了要搜索的,其它都排除 $wp_query->query_vars['post_type'] ="type_product"; //还可添加其它条件,比如要搜索的文章类型$wp_query->query_vars['post_type'] ="product"; } } add_filter('pre_get_posts', 'return_only_selected_category');
参考2:
//文章显示过滤 function hwl_home_pagesize( $query ) { $num_per_page = get_field('cate_num' , 'options'); if(empty($num_per_page)){ $num_per_page = 12; } if ( is_archive() ) { $query->set( 'posts_per_page', $num_per_page); return; } } add_action( 'pre_get_posts', 'hwl_home_pagesize', $num_per_page);
参考3:
// Exclude Pages from Search Results function excludePages($query) { if ($query->is_search) { $query->set('post_type', array('post', 'custom-post-type')); } return $query; } if (!is_admin()) add_filter('pre_get_posts','excludePages');
本文介绍如何使用WordPress的pre_get_posts钩子,通过PHP代码实现文章的精确筛选与展示,包括按分类显示文章、调整归档页的文章数量及从搜索结果中排除特定页面。
176

被折叠的 条评论
为什么被折叠?



