php - wp_query 类别和主题标签

标签 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();
                ?>

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

最佳答案

正确的方法是限制 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();

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

关于php - wp_query 类别和主题标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33838424/

相关文章:

wordpress - 如何在 WordPress 中制作框架?

wordpress - WordPress 的 .htaccess 和 SEO 是如何构建的?

php - 通过url中的特定字段从MySQL数据库表中获取数据

php - 如何使用 PHP API 和 AngularJS 2 服务正确处理/获取正确的 JSON 响应?

php - 使用 exec() 运行 unix `at` 命令

php - 本地 Apache 服务器 mod_rewrite/pretty 链接问题

php - 实体、存储库和组合 - 依赖注入(inject)

php - PHP 中的数组输入是否保证 POST 中输入的顺序?

wordpress - 在 WP_Query 中包含子项

php - 如何在数据库中保存为文本类型时比较日期