问题描述
我有 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>';
}
谢谢!
解决方法
您可以从术语对象中获取 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>';
}