一个WP_QUERY,它将查找2周前的帖子或具有特定元值的帖子

时间:2016-01-18 作者:Pete

我正在寻找一种基本上在date_query 以及meta_query. 基本上我想把两者结合起来WP_Query\'s

Get the posts from the last two weeks

$args = array(
    \'post_type\'  => \'post\',
    \'orderby\'    => \'date\',
    \'posts_per_page\' => -1,
    \'date_query\' => array(
        array(
            \'after\' => \'2 weeks ago\'
        )
    )
);

Get posts with certain meta_value, such as sticky = \'true\'

$args = array(
    \'post_type\'  => \'post\',
    \'orderby\'    => \'date\',
    \'posts_per_page\' => -1,
    \'meta_query\' => array(
        array(
            \'key\'     => \'sticky\',
            \'value\'   => true,
            \'type\'    => \'BOOLEAN\',
        ),
    ),
);
如何将这两个查询合并为一个查询——但是如果一篇文章满足日期或meta\\u查询要求,那么它就会被选中。

1 个回复
最合适的回答,由SO网友:Pieter Goosen 整理而成

通过使用post clauses filters 以及重写生成的SQL查询。

您还可以运行3个查询,

一个非常精简的查询,可以从date_query

一个非常精简的查询,可以从meta_query

最后一次查询,以获取完整的查询对象。如果您想对查询分页,这将特别有助于分页。这还可以按顺序正确排序帖子。

您可以尝试以下方法

$defaults = [
    \'post_type\'      => \'post\',
    \'orderby\'        => \'date\',
    \'posts_per_page\' => -1,
    \'fields\'         => \'ids\' // Only return post ID\'s for performance
];

// Query 1
$date_query = [
    [
        \'after\' => \'2 weeks ago\'
    ]
];
$query1 = new WP_Query( array_merge( $date_query, $defaults ) );

// Query 2
$meta_query = [
    [
        \'key\'     => \'sticky\',
        \'value\'   => true,
        \'type\'    => \'BOOLEAN\',
    ]
];
$query2 = new WP_Query( array_merge( $meta_query, $defaults ) );

// Final query
// Get all the post ID\'s from the two queries and merge into one array
$ids = array_merge( $query1->posts, $query2->posts )
// Make sure we have an array of id\'s before continueing to avoid unexpected results
if ( $ids ) {
    // Remove possible duplicates
    $ids = array_unique( $ids );
    // Set fields back to all to get full post objects
    $defaults[\'fields\']    = \'all\';
    // Add extra parametes
    $defaults[\'post__in\']    = $ids; // Set the array of ids to post__in
    // $defaults[\'order\']    = \'ASC\'; // If you want to keep the post order according to post__in
    //$defaults[\'orderby\'] = \'post_in\'; // If you want to keep the post order in post__in

    // Run our query
    $q = new WP_Query( $defaults );
    // You can now run your loop