首页 > 解决方案 > 尝试使用当前帖子的标签查询帖子

问题描述

我正在创建一个具有多个帖子关系的网站。对于我使用 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();功能似乎可以正常工作,因为它按预期输出标签。但是,在将其插入查询时,它似乎不起作用。它只输出所有帖子,无论标签如何。

标签: phpwordpress

解决方案


我有一个可行的解决方案。希望这对某人有帮助。

代码:

<?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
    }?>

推荐阅读