questions

Get tags IDs in post

Rate this post

I have this code for the tag list in WordPress posts, where I add an external link next to each tag:

$terms = get_the_tags();

    if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) { 
        echo '<ul>';

        foreach ( $terms as $term ) {
            $link = get_term_link( $term );
            if ( is_wp_error( $link ) ) {
                continue;
            }

            $external_link = 'https://www......../?search3=' . $term->name . '&pn=xxxx';

            echo '<li>' .
            '<a href="' . esc_url( $link ) . '" rel="tag">' . $term->name . '</a> ' .
            '<a href="' . esc_url( $external_link ) . '" target="_blank">img</a>' .
            '</li>';
        }

        echo '</ul>';
        }

Now I have added a custom field to tags, its slug is “_tag_link”. I’d like to replace the actual “$external_link” with the custom field “_tag_link” and show it only if it exists. I changed the code this way but I don’t know how to get “$term_id” (and if the code is correct in general):

$terms = get_the_tags();

    if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) { 
        echo '<ul>';

        foreach ( $terms as $term ) {
            $link = get_term_link( $term );
            if ( is_wp_error( $link ) ) {
                continue;
            }

            echo '<li>' .
            '<a href="' . esc_url( $link ) . '" rel="tag">' . $term->name . '</a> ';
            if ( $external_link = get_term_meta($term_id, '_tag_link', true) ) { 
                echo '<a href="' . $external_link .'" target="_blank" rel="noopener">img</a>';
            }
            echo '</li>';
        }

        echo '</ul>';
        }

Thank you!

 

✔️Solution:

You can get term_id from the term object:

$terms = get_the_tags();

if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) { 
    echo '<ul>';

    foreach ( $terms as $term ) {
        $link = get_term_link( $term );

        if ( is_wp_error( $link ) ) {
            continue;
        }

        echo '<li>' . '<a href="' . esc_url( $link ) . '" rel="tag">' . $term->name . '</a> ';

        if ( $external_link = get_term_meta( $term->term_id, '_tag_link', true ) ) { 
            echo '<a href="' . $external_link . '" target="_blank" rel="noopener">img</a>';
        }

        echo '</li>';
    }

    echo '</ul>';
}

Leave a Reply

Your email address will not be published.

Back to top button