doujie7497 2019-01-26 19:00
浏览 94
已采纳

在Wordpress标签列表中添加外部链接,并获取没有自己链接的标签名称

I have this code for the tag list in Wordpress:

$tags_list = get_the_tag_list( '', __( '</li><li>', 'wp-theme') );
if ( $tags_list ) {
    printf( '' . __( '<ul><li>%1$s</li></ul>', 'wp-theme' ) . '', $tags_list );
        }

It becomes this HTML:

<ul>
<li><a href="http://internal-link/tag1/>TAG NAME 1</a></li>
<li><a href="http://internal-link/tag2/>TAG NAME 2</a></li>
</ul>

But I need to get this:

<ul>
<li><a href="http://internal-link/tag1/>TAG NAME 1</a> <a href="https://external-link/?search=TAG+NAME+1">img</a></li>
<li><a href="http://internal-link/tag2/>TAG NAME 2</a> <a href="https://external-link/?search=TAG+NAME+2">img</a></li>
</ul>

How should I edit the code above to add the external link after each tag and how do I get the tag name without its own link, so I can add it to the external link?

Thank you!

  • 写回答

1条回答 默认 最新

  • dongzhouhao4316 2019-01-28 07:56
    关注

    Instead of using get_the_tag_list(), you can manually generate the output:

    $terms = get_the_tags();
    
    if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) { // Check if $terms is OK.
        echo '<ul>';
    
        foreach ( $terms as $term ) {
            $link = get_term_link( $term );
            if ( is_wp_error( $link ) ) {
                continue;
            }
    
            // Here, just change the URL.
            $external_link = 'https://external-link/?search=' . $term->name;
    
            echo '<li>' .
                '<a href="' . esc_url( $link ) . '" rel="tag">' . $term->name . '</a>' .
                ' <a href="' . esc_url( $external_link ) . '">' . $term->name . '</a>' .
            '</li>';
        }
    
        echo '</ul>';
    }
    

    And that would replace your existing code:

    $tags_list = get_the_tag_list( '', __( '</li><li>', 'wp-theme' ) );
    if ( $tags_list ) {
        printf( '' . __( '<ul><li>%1$s</li></ul>', 'wp-theme' ) . '', $tags_list );
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?