首页 > 解决方案 > 如何将 wordpress 查询限制为仅包含 1 个共享标签或图像的帖子?

问题描述

我编写了一个小脚本来检索和显示与主帖子相同类别的 4 个随机帖子。问题是该类别中的 6 个帖子(标记为 Q&A)具有相同的图像。因此,如果脚本显示两个或三个问答帖子,它会显示相同的图像 2-3 次。

是否可以将查询限制为从一个类别中检索 4 个帖子,但仅包括 1 个共享 Q&A 标签和图像的帖子?

这是我目前正在使用的功能:

function wcr_related_posts($args) {
    global $post;
    $category = get_the_category(); 

    // default args
    $common_args = array(
        'numberposts'   => 4,
        'orderby'          => 'rand',
        'order'            => 'DESC',
        'meta_query' => array(
            'key' => '_thumbnail_id',
            'compare' => 'EXISTS'),
        'post_type'        => "post",
        'post_status'      => "publish",
        'post__not_in'     => array($post->ID)
    );

    $cat_search_args = array(
        'tax_query' => array(
            array(
                'taxonomy' => 'category',
                'field'    => 'name',
                'terms'    => $category[0]->name
            )
        ));
    $feature_posts_args = array(
        'post__in' => array( 705, 1883, 4897, 3967, 3766, 3585, 2698, 2412, 2203, 2575, 282, 4040)

                );

    if ( in_array($category[0]->name, array('Erotic Hypnosis', 'Dominance and Submission', 'Sexual Health'))&& is_page()!== true){
            $args = wp_parse_args($cat_search_args, $common_args);
        }else {
            $args = wp_parse_args($feature_posts_args, $common_args);
        }

    //  use for diagnostics only
    //  print_r($args); 

    // query
    $related_posts = get_posts($args);

    // get template
    include_once( __DIR__ . '/relatedposts-template.php');

    wp_reset_postdata();

}

标签: wordpresstagsrelated-posts

解决方案


推荐阅读