【问题标题】:Get tags IDs in post在帖子中获取标签 ID
【发布时间】:2021-01-31 20:28:40
【问题描述】:

我在 Wordpress 帖子中有标签列表的代码,我在每个标签旁边添加了一个外部链接:

$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>';
        }

现在我为标签添加了一个自定义字段,它的 slug 是“_tag_link”。我想用自定义字段“_tag_link”替换实际的“$external_link”,并仅在它存在时显示它。 我以这种方式更改了代码,但我不知道如何获取“$term_id”(以及代码是否正确):

$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>';
        }

谢谢!

【问题讨论】:

    标签: php wordpress tags wordpress-theming custom-fields


    【解决方案1】:

    您可以从术语对象中获取term_id

    $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>';
    }
    

    【讨论】:

    • 这太简单了,我没有去研究它!非常感谢!!
    猜你喜欢
    • 2021-09-11
    • 2010-12-04
    • 2015-06-17
    • 2015-12-27
    • 1970-01-01
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多