【问题标题】:Exclude uncategorized posts from search and archive pages从搜索和存档页面中排除未分类的帖子
【发布时间】:2015-12-15 15:28:38
【问题描述】:

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

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

我一直在徒劳地寻找插件。我想肯定有一些自定义的php,但我的技术不是很深。

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

【问题讨论】:

    标签: wordpress


    【解决方案1】:

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

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

    <?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; ?>
    

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

    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;
    }
    

    请注意:您也可以在此处使用逗号分隔类别:

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

    【讨论】:

    • 非常感谢您的回答,这真的很棒。经过更多的挖掘,我确实找到了一个有效的插件 - 称为 Advanced Category Excluder,但您的解决方案更加优雅,所以我会试一试,让您知道它是怎么回事,再次感谢!
    • 再次嗨,我无法让代码修改工作 - 我想我使用的主题有点不同,例如没有 archive.php 文件,但你启发了我了解更多关于 php - 再次感谢!
    • 不,我遇到了错误。这是 index.php 中的循环代码:
    • &lt;?php if (have_posts()) : ?&gt; &lt;!-- loops-wrapper --&gt; &lt;div id="loops-wrapper" class="loops-wrapper &lt;?php echo $themify-&gt;layout . ' ' . $themify-&gt;post_layout; ?&gt;"&gt; &lt;?php while (have_posts()) : the_post(); ?&gt; &lt;?php if(is_search()): ?&gt; &lt;?php get_template_part( 'includes/loop' , 'search'); ?&gt; &lt;?php else: ?&gt; &lt;?php get_template_part( 'includes/loop' , 'index'); ?&gt; &lt;?php endif; ?&gt; &lt;?php endwhile; ?&gt; &lt;/div&gt; &lt;!-- /loops-wrapper --&gt; &lt;?php get_template_part( 'includes/pagination'); ?&gt;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    • 2015-05-10
    • 1970-01-01
    • 1970-01-01
    • 2019-04-14
    • 2017-08-27
    相关资源
    最近更新 更多