【问题标题】:Remove Featured Post from Wordpress Loop从 Wordpress 循环中删除精选帖子
【发布时间】:2020-02-27 02:45:12
【问题描述】:

我正在尝试找出一种方法来从“最近的帖子”页面中排除标记为“精选”的帖子。

如下所示,我最近的帖子页面仅显示来自 2 个类别(cat1 和 cat2)的帖子。问题是,有时,我会将帖子添加到以下类别之一,并将其​​标记为“特色链接”或其他内容。因此,当您查看页面时,您基本上会在标题(循环外)和正文内(循环内)看到特色帖子。我将如何删除循环中的精选帖子?

              <?php
                // args query
                $args = array(
                    'post_type'      => 'post',
                    'posts_per_page' => 3,
                    'order'          => 'DESC',  
                    // display only posts in specifics categories (slug)
                    'category_name' => 'cat1, cat2' 
                ); 

                // custom query
                $recent_posts = new WP_Query($args);

                // check that we have results
                if($recent_posts->have_posts()) : ?>

            <?php 
                // start loop
                while ($recent_posts->have_posts() ) : $recent_posts->the_post();
            ?>

对于任何想知道的人,我尝试了以下方法,但没有成功:

                $args = array(
                    'post_type'      => 'post',
                    'posts_per_page' => 3,
                    'order'          => 'DESC',  
                    // display only posts in specifics categories (slug)
                    'category_name' => 'cat1, cat2',
                    'meta_query' => array(
                        array(
                            'key'     => 'featured',
                            'value'   => 'yes',
                            'compare' => 'NOT LIKE',
                        ),
                    ),  
                ); 

当添加其他人建议的“meta_query”时,页面似乎停止显示结果。

您知道如何正确地写出这一点并可能提供其他替代解决方案吗?

谢谢。

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    测试工作良好。只需将'compare' =&gt; 'NOT LIKE' 替换为'compare' =&gt; 'NOT EXISTS'。希望对您有所帮助。

    // args
    $args = array(
        'numberposts'   => 3,
        'post_type'     => 'post',
        'meta_query' => array(
            array(
                'key'     => 'featured',
                'value'   => 'yes',
                'compare' => 'NOT EXISTS',
            ),
        ),
    );
    
    // query
    $the_query = new WP_Query( $args );
    
     if( $the_query->have_posts() ):
     while( $the_query->have_posts() ) : $the_query->the_post();
        echo the_title(); 
     endwhile;
     endif;
    
     wp_reset_query();
    

    【讨论】:

      【解决方案2】:

      另一种方法是您可以在您的wp_query 中使用'post__not_in' =&gt; array (//post ids you want to exclude)

      【讨论】:

        猜你喜欢
        • 2011-02-08
        • 1970-01-01
        • 2017-08-25
        • 1970-01-01
        • 2010-12-03
        • 2016-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多