从搜索和存档页面中排除未分类的帖子 [英] Exclude uncategorized posts from search and archive pages

查看:37
本文介绍了从搜索和存档页面中排除未分类的帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Wordpress 网站中,我想防止任何未分类的帖子出现在网站搜索和存档页面中 - 包括最近帖子的首页.

我希望未分类帖子可见的唯一地方是实际帖子本身,以及作者存档页面上,例如 example.com/author/authorName

我徒劳地寻找了一个插件.我估计肯定有一些自定义的php,但我的技能没有那么深.

非常感谢任何帮助或线索!

解决方案

您必须从 archive.phpindex.php 中的循环中排除类别.此示例使用类别 ID 编号,您可以通过转至 帖子 >> 类别 找到该编号.您会看到每个类别的 ID.

在上面提到的文件中,找到循环

<?php $query = new WP_Query( 'cat=-1' );?>//这是你排除的地方.您可以用逗号分隔多个类别:'cat=-1,-2,-3' 等<?php if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();?><div class="post"><!-- 这是帖子内容-使用您使用的任何主题-->

<?php endwhile;wp_reset_postdata();否则:?><p><?php _e('抱歉,没有符合您条件的帖子.');?></p><?php endif;?>

至于搜索结果,试试这个.这将进入 functions.php(我还没有测试过,所以如果有问题请告诉我).

add_filter( 'pre_get_posts' , 'search_exclude' );函数 search_exclude( $query ) {if( $query->is_admin )返回 $query;if( $query->is_search ) {$query->set('category__not_in', array(1));//类别 ID}返回 $query;}

请注意:您也可以通过以下方式在此处用逗号分隔类别:

$query->set('category__not_in', array(1,2,3));

In my Wordpress site I want to prevent any uncategorized posts from showing up in site searches and in archive pages - including the front page of recent posts.

The only places that I want uncategorised posts to be visible are the actual posts themselves, and on the author archive pages, eg example.com/author/authorName

I have looked in vain for a plugin. I reckon there must be some custom php, but my skills are not that deep.

Any help or clues greatly appreciated!

解决方案

You have to exclude the category from the loop in your archive.php and index.php. This example uses category ID numbers, which you can find by going to Posts >> Categories. You'll see the ID for each category.

In your files mentioned above, find the loop

<?php $query = new WP_Query( 'cat=-1' ); ?> // This is where you exclude. You can comma separate multiple categories : 'cat=-1,-2,-3' etc
 <?php if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>

 <div class="post">

 <!-- Here is the post content - use whatever your theme is using -->

 </div> 

 <?php endwhile; 
 wp_reset_postdata();
 else : ?>
 <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
 <?php endif; ?>

As for the search results, try this. This will go in functions.php (I haven't tested it so let me know if there are issues).

add_filter( 'pre_get_posts' , 'search_exclude' );
function search_exclude( $query ) {

if( $query->is_admin )
return $query;

if( $query->is_search ) {
$query->set( 'category__not_in' , array( 1 ) ); // Category ID
}
return $query;
}

Please note: you can also comma separate the categories here by doing this:

$query->set( 'category__not_in' , array( 1,2,3 ) );

这篇关于从搜索和存档页面中排除未分类的帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆