wp-query 类别并有标签

Ty *_* T. 2 php wordpress

我正在尝试使用 wp_query 查询 wordpress 中的帖子。我想使用 has_tag 将帖子放在一个类别中并进行查询。我试着用

$args = array (
                    'post_type'  => array( 'post' ),
                    'category_name' => 'footer',
                );
                // The Query
                $social = new WP_Query( $args );
                // The Loop
                if ( $social->have_posts()&&has_tag('social') ) {
                    while ( $social->have_posts() ) {
                        $social->the_post();
                        the_content();
                    }
                } rewind_posts();
                ?>
Run Code Online (Sandbox Code Playgroud)

但这会加载所有帖子,而不仅仅是显示带有标签的帖子。

Tim*_*han 5

正确的方法是限制 WP_Query 本身。

例如

$args = array(
    'post_type'  => array( 'post' ),
    'category_name' => 'footer',
    'tag' => 'social'
);

$social = new WP_Query( $args );

if ( $social->have_posts() ) {
    while ( $social->have_posts() ) {
        $social->the_post();
        the_content();
    }
}

wp_reset_postdata();
Run Code Online (Sandbox Code Playgroud)

要使用 has_tag,您需要先设置您的全局帖子数据,例如 setup_postdata( $social ),这会产生大量的条件和循环开销,只是为了在您可以在查询本身中执行时过滤您的结果。