【问题标题】:Get a tag assigned to custom post type获取分配给自定义帖子类型的标签
【发布时间】:2021-01-24 17:31:18
【问题描述】:

我正在使用WooCommerce,并已使用标签“电子”标记了products(自定义帖子类型为product)之一。

我现在正在尝试循环并获取分配给该帖子的标签,但目前,当尝试转储数据时,我返回bool(false)

这是我的方法:

<?php
$args = array(
    'post_type' => 'product',
    'p' => $product_name,
    'posts_per_page' => 1
);

$loop = new WP_Query($args);

while ($loop->have_posts()):
    $loop->the_post();

    $posttags = get_the_tags();
    if ($posttags)
    {
        foreach ($posttags as $tag)
        {
            echo $tag->name;
        }
    }

    var_dump($posttags);

endwhile;
wp_reset_query();

?>
<?php
$args = array(
    'post_type' => 'product',
    'p' => $product_name,
    'posts_per_page' => 1
);

$loop = new WP_Query($args);

while ($loop->have_posts()):
    $loop->the_post();

    $posttags = get_the_tags();
    if ($posttags)
    {
        foreach ($posttags as $tag)
        {
            echo $tag->name;
        }
    }

    var_dump($posttags);

endwhile;
wp_reset_query();

?>

试过了:

<?php
global $post;

$args = array(
    'post_type' => 'product',
    'p' => $product_name,
    'posts_per_page' => 1
);

$loop = new WP_Query($args);

$product_tags = get_the_terms($post, 'product_tag');

while ($loop->have_posts()):
    $loop->the_post();

    if ($product_tags){
        foreach ($product_tags as $tag){
            echo $tag->name;
        }
    }

endwhile;
wp_reset_query(); ?>

但上面没有回应任何东西?

【问题讨论】:

    标签: php wordpress custom-post-type


    【解决方案1】:

    我相信get_the_tags() 仅用于帖子标签,而不是 WooCommerce 的产品标签。对于 WooCommerce,分类应为 product_tag。你可以使用

    <?php
    $product_tags = get_the_terms( $post, 'product_tag' );
    ?>
    

    获取标签,然后根据需要循环它们。

    完整代码示例:

    <?php
    global $post;
    
    $args = array(
        'post_type' => 'product',
        'p' => $product_name,
        'posts_per_page' => 1
    );
    
    $loop = new WP_Query($args);
    
    while ($loop->have_posts()):
        $loop->the_post();
    
        $product_tags = get_the_terms($post, 'product_tag');
    
        if ($product_tags && !is_wp_error($product_tags){
            foreach ($product_tags as $tag){
                echo $tag->name;
            }
        }
    
    endwhile;
    wp_reset_query(); ?>
    

    【讨论】:

    • 嗨,Kevin,我尝试了你的方法,可能只是我实施不正确,但它仍然没有对我产生任何影响。我编辑了我的问题以展示我的方法
    • 嗨,请尝试将get_the_terms() 放入循环中。这是因为在您的情况下,$post 对象仅在循环内可用。 (我的答案已被编辑以反映完整的代码)
    猜你喜欢
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2019-11-04
    • 2023-04-03
    • 2016-10-28
    • 2017-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多