[英]Trying to query posts with the tags of current post
我正在創建一個具有多個職位關系的網站。 對於帖子之間的交叉引用,我使用了wordpress標簽。 現在,當我在一個具有多個標簽的帖子上時,我想查詢所有具有兩個標簽的帖子。 因此,當前帖子具有'tag1'
和'tag2'
,應該有僅包含這兩個標簽的帖子列表
請參閱下面的代碼,以查看我無法使用的解決方案。 我認為獲取當前標簽ID的列表是個好主意。 為此,我使用了Wordpress Codex提供的標准解決方案,然后創建了可以在查詢中使用的自定義函數。 不幸的是,這似乎不是正確的解決方案,函數listtags確實按預期輸出了ID。
<?php
function list_tags(){
$posttags = get_the_tags();
foreach($posttags as $tag) {
echo $tag->term_id . ' ';
}
}
$listtags = list_tags();
echo $listtags . ' ';
$tag_query = new WP_Query( array(
'post_type' => 'les',
'order' => 'ASC',
'tag__and' => array( $post_tag ),
) );
// The Loop
if ( $tag_query->have_posts() ) {
while ( $tag_query->have_posts() ) {
$tag_query->the_post(); ?>
<div class="les-container" style="background-color: red; height:200px;">
<div class="container">
<div class="row posts-align">
<h2><?php the_title(); ?></h2>
<?php the_content(); ?>
</div>
</div>
</div>
<?php } wp_reset_postdata();
} else {
// no posts found
}?>
list_tags();
函數似乎正常工作,因為它按預期方式輸出標簽。 但是,將其插入查詢中似乎無效。 它只輸出所有帖子,而不管標簽如何。
tag_slug__and用於子彈。 tag__和用於ID。 您可以在此處找到更多信息-https: //code.tutsplus.com/tutorials/wp_query-arguments-categories-and-tags--cms-23070
我有一個可行的解決方案。 希望這對某人有幫助。
碼:
<?php
$tags = array();
$posttags = get_the_tags();
if ($posttags) {
foreach($posttags as $tag) {
$tags[] = $tag->term_id;
}
}
$tag_query = new WP_Query( array(
'post_type' => 'les',
'order' => 'ASC',
'tag__and' => $tags,
'post_parent' => 0,
) );
// The Loop
if ( $tag_query->have_posts() ) {
while ( $tag_query->have_posts() ) {
$tag_query->the_post(); ?>
<div class="les-container" style="background-color: red; height:200px;">
<div class="container">
<div class="row posts-align">
<h2><?php the_title(); ?></h2>
<?php the_content(); ?>
</div>
</div>
</div>
<?php }
wp_reset_postdata();
} else {
// no posts found
}?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.