1

I want to display product assigned terms, wrapped in link/anchor MarkUp, in my sidebar on a page as a widget. I am not getting the correct tag URL. Code returns visited product URL instead of listed tags URL.

Here is the problematic part of the code. What is the correct use of get_the_terms()?

$custom_terms = get_the_terms( 0, 'product_tag' );
if ( $custom_terms ) {
    foreach ( $custom_terms as $custom_term ) {
        echo '<a href="'
            . esc_url( $term_link )
            . '" style="font-size: 8pt;">'
            . $custom_term->name
            . '</a>';
    }
}

I guess that something i wrong with esc_url( $term_link ), but what?

4
  • 1
    $term_link is not set Oct 3, 2014 at 11:24
  • Thank you Mark. You were right. I will post correct snippet now.
    – pendjer
    Oct 8, 2014 at 8:32
  • 1
    Note: Only because a question contains the word Woocommerce it doesn't justify close and/or down-votes. Just saying.. Oct 8, 2014 at 10:00
  • $term_link is still not set. The correct snippet appears to have never been posted.
    – s_ha_dum
    Oct 11, 2014 at 18:24

2 Answers 2

2

Keep in mind that the return value of get_the_terms() can be of the type of

array|WP_Error

Your snippet should check if you get the correct type returned

$terms = get_the_terms( 0, 'product_tag' );
if (
    ! is_wp_error( $terms )
    AND is_array( $terms )
    AND ! empty( $terms )
    )
{
    foreach( $terms as $term )
        printf(
            '<a href="%s" style="font-size: 8pt; margin-right:5px;">%s</a>',
            esc_url( get_term_link( $term ) ),
            $term
        );
}
1
  • 1
    Hi Kaiser. Thank you for the contribution. I make it your way.
    – pendjer
    Oct 13, 2014 at 16:00
0

Thanks to Mark, I solve this successfully.

Update: Thanks to Kaiser part of the code has been updated. Here is the final code.

<?php 

$custom_terms = get_the_terms(0,'product_tag');
if (
          ! is_wp_error( $custom_terms )
          AND is_array( $custom_terms )
          AND ! empty( $custom_terms )
         )
          {
            foreach ($custom_terms as $custom_term) {

            $term_link = get_term_link( $custom_term );
                echo '<a href="'. esc_url( $term_link ). '" style="font-size: 8pt; margin-right:5px;">'.$custom_term->name.'</a>';
            }
        }

        ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.