I'm using WooCommerce
and have tagged one of products
(custom post type is product
) with the tag "electronic".
I'm now trying to loop through and obtain the tag assigned to that post, but currently, when trying to dump the data, I'm returned with bool(false)
.
Here is my approach:
<?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();
?>
Have tried:
<?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(); ?>
But the above doesn't echo anything?
I believe get_the_tags()
is used only for post tags, not WooCommerce's product tags. For WooCommerce, the taxonomy should be product_tag
. You may use
<?php
$product_tags = get_the_terms( $post, 'product_tag' );
?>
to get the tags and then loop over them as required.
Full code example:
<?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(); ?>