【问题标题】:Exclude Featured Posts in Wordpress 'Recent Posts' Function在 Wordpress 的“最近帖子”功能中排除精选帖子
【发布时间】:2019-08-09 20:42:39
【问题描述】:

我可以使用wp_get_recent_posts 函数中的“排除”数组来排除精选帖子吗?我有一个名为 NS Featured Posts 的插件,它通过 wp 查询中的一个键提取精选帖子,即:

$custom_query = new WP_Query( 
    array(
        'post_type' => 'post', 
        'meta_key'   => '_is_ns_featured_post',
        'meta_value' => 'yes'
    ) 
);

我能否以某种方式使用它来定位和排除 wp_get_recent_posts 调用中的 NS 精选帖子,例如:

$recent_posts = wp_get_recent_posts(array(
        'numberposts' => 3,
        'exclude' => (the ns featured posts)
    ));

感谢您的任何见解。

【问题讨论】:

    标签: php wordpress loops


    【解决方案1】:

    所以我现在对其进行了测试,并且无法在一个查询中获取没有特定元键的帖子。

    但是:您可以像这样从另一个查询中排除它们:

        $featured_posts = get_posts( [
            'meta_key' => '_is_ns_featured_post',
            'meta_value' => 'yes',
            'fields'     => 'ids',
        ] );
    
        query_posts( array( 'post__not_in' => $featured_posts ) );
    
        while ( have_posts() ) : the_post();
            $output .= '<li>'.get_the_title().'</li>';
        endwhile;
    
        wp_reset_query();
    

    【讨论】:

    • 谢谢,但我试过了(没用),这就是为什么我想知道是否可以使用排除选项来执行此操作。看起来这应该是一个相当普遍的逻辑......
    • Jep,我应该测试一下。仅通过查询空元数据确实不起作用。编辑了我的答案。
    【解决方案2】:

    wp_get_recent_posts() 等函数可以接受与WP_Query 相同的所有参数。虽然文档只列出了少数参数,但您可以使用完整的参数集。

    您曾建议在您的查询中使用exclude,但是这将希望排除帖子的 ID。你当然可以先抓住那些,但这不是最有效的解决方案。

    在单个查询中执行此操作的方法是使用元查询选项。这些帖子被标记为元键,元查询将允许您排除这些。您需要检查元键是否存在以及值是否为“是”。

    例子:

    $recent_posts = wp_get_recent_posts( array(
        'numberposts' => 3,
        'meta_query' => array(
            'relation' => 'OR',
            array(
                'key' => '_is_ns_featured_post',
                'value' => 'yes',
                'compare' => '!=',
            ),
            array(
                'key' => '_is_ns_featured_post',
                'compare' => 'NOT EXISTS',
            ),
        )
    ) );
    

    参考:https://codex.wordpress.org/Class_Reference/WP_Meta_Query

    【讨论】:

    • 这实际上与我在实际测试之前的答案相似。未设置未精选帖子的元键/值,因此这不起作用。
    • @pjldesign 我已经更新了答案以解决其他评论者的观点。
    • @user127091 你是对的!我刚刚更新了我的答案,包括检查元键是否确实存在。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-17
    • 2017-08-25
    • 2014-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多