首页 > 解决方案 > 从 Wordpress 循环中删除精选帖子

问题描述

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

正如您在下面看到的,我最近的帖子页面仅显示来自 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”内容时,页面似乎停止显示结果。

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

谢谢。

标签: phpwordpress

解决方案


测试工作良好。只需替换'compare' => 'NOT LIKE''compare' => '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();

推荐阅读