我写了一些代码,可以自动创建一些帖子并为它们添加标签。我可以在“所有帖子”管理面板中看到标签,我可以单击帖子的“标签”链接以获取带有标签的帖子。
但是,在我使用 $wp_query 编写的插件中,无论我传入什么参数,我都会返回完整的帖子列表,无论它们是否具有我正在寻找的标签。
这是我的代码:
// Now retrieve all items matching this brand name . . .
$query=new WP_Query(array('posts_per_page=5', array('tag' => array($brand_name))));
// The Loop
while ( $query->have_posts() ) : $query->the_post();
echo '<li>';
the_title();
echo '</li>';
endwhile;
// Reset Post Data
wp_reset_postdata();
当我告诉它只返回 5 个时,这会产生 10 个结果。实际上我应该只返回 2 个帖子,因为这是带有标签的总数。
网上查了下好像有很多人有同样的问题但是没有解决办法。我一定已经尝试了大约 10 种不同的方式来指定标签,但返回的帖子数量是错误的这一事实表明我要么完全错了,要么存在某种错误。如果有帮助,Wordpress 版本是 3.4.1。
任何 Wordpress 专业人士都可以阐明这一点吗?
提前致谢!
在这里找到答案 - https://codex.wordpress.org/Template_Tags/get_posts
以下示例显示在“流派”下标有“爵士乐”的帖子 自定义分类法,使用“tax_query”
$args = array(
'tax_query' => array(
array(
'taxonomy' => 'genre',
'field' => 'slug',
'terms' => 'jazz'
)
)
);
$postslist = get_posts( $args );
所以对你来说会是
$args = array(
'posts_per_page' => 5,
'tax_query' => array(
array(
'taxonomy' => 'post_tag',
'field' => 'slug',
'terms' => sanitize_title( $brand_name )
)
)
);
$postslist = get_posts( $args );
试试这个
$original_query = $wp_query;
$wp_query = null;
$args = array('posts_per_page' => 5, 'tag' => $brand_name);
$wp_query = new WP_Query($args);
if (have_posts()) :
while (have_posts()) : the_post();
echo '<li>';
the_title();
echo '</li>';
endwhile;
endif;
$wp_query = null;
$wp_query = $original_query;
wp_reset_postdata();
在你的代码中,尝试:
$query=new WP_Query(array('posts_per_page=5', 'tag' => $brand_name));
代替:
$query=new WP_Query(array('posts_per_page=5', array('tag' => array($brand_name))));
有关详细信息,请参阅https://codex.wordpress.org/Class_Reference/WP_Query#Tag_Parameters (正如最近的重复帖子中提到的那样)。
注意: $brand_name 可以是字符串数组,或者逗号分隔值等,上面的代码应该可以工作。
或者,尝试:
$myPosts = get_posts(array('tag' => $brand_name));
花了我一段时间。这就是您如何从帖子中获得 3 个具有相同标签之一的随机帖子
$post = get_post(); // if you don't have $post->ID already
$tag_ids = wp_get_post_tags( $post->ID, array( "fields" => "ids" ) ); // current tags
$args = array(
"numberposts" => 3,
"orderby" => "rand",
"post__not_in" => array( $post->ID ), //exclude current
"post_type" => "article", // defaults to "post", also note "any" option
"tax_query" => array(
array(
"taxonomy" => "post_tag",
"field" => "term_id",
"terms" => $tag_ids
)
)
);
$posts = get_posts( $args ); // getting posts
如果它仍然对您不起作用,可以查看
$args
生成的 sql 请求以进一步排除故障
$q = new WP_Query($args);
echo $q->request;
SELECT SQL_CALC_FOUND_ROWS wpwg_posts.ID FROM wpwg_posts WHERE 1=1 AND wpwg_posts.ID NOT IN (0) AND ( 0 = 1) AND ((wpwg_posts.post_type = 'p' AND (wpwg_posts.post_status = 'publish' OR wpwg_posts.post_status = 'private'))) 按 wpwg_posts.ID 分组 按 RAND() 排序 LIMIT 0, 10
这个sql请求,我还是看不到帖子