在 WordPress PHP 中工作,我试图将一个值传递到元素的类标签中
<div class="element-item"></div>
成为像
<div class="element-item comedy"></div>
代码:
$term = get_the_term_list( get_the_ID(), 'type' );
echo '<div class="element-item '.$term.'">';
值从类标签中弹出并显示在页面上:
我检查了源代码,似乎我将整个链接传递给了类标签:
<div class="element-item " .<a="" href="http://www.domain.ca/type/meat/" rel="tag" style="position: absolute; left: 0px; top: 0px;">Canadian</div>
为什么会发生这种情况以及如何解决?
试试这个方法,也许会对你有帮助
$html_output = '<div class="element-item ' . $term . '">';
echo $html_output;
尝试这样
echo "<div class="element-item $term>";
或
你可以在 javascript 的帮助下做到这一点,就像这样
$(function(){
$('.element-item').addClass('<?php echo $term ?>');
});
如果您遇到任何问题,请告诉我
您已经根据返回值正确识别了问题。
问题在这里:
$term = get_the_term_list( get_the_ID(), 'type' );
get_the_term_list()
将返回一个 HTML 字符串,如函数文档中所述:https://codex.wordpress.org/Function_Reference/get_the_term_list
我建议采用以下方法:
// We're going to place all of our classes into this array.
$classes = array( 'element-item' );
// Get terms assigned to post.
$terms = get_the_terms( get_the_ID(), 'type' );
// Check terms were found.
if ( $terms && ! is_wp_error( $terms ) ) {
// Loop through each found term and add it to the array of classes.
foreach ( $terms as $term ) {
$classes[] = $term->slug;
}
}
// Convert the array of classes into a string separated by spaces.
// Escape the value before outputting inside the attribute tag.
printf( '<div class="%s">', esc_attr( implode( ' ', $classes ) ) );
进一步阅读:https://codex.wordpress.org/Function_Reference/get_the_terms