如何在WordPress中将变量传递到HTML类标记中

8aqjt8rx  于 11个月前  发布在  WordPress
关注(0)|答案(3)|浏览(196)

在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.'">';


值从class标记中弹出并显示在页面上:


的数据
我检查了源代码,似乎我传递了整个链接到class标签:

<div class="element-item " .<a="" href="http://www.domain.ca/type/meat/" rel="tag" style="position: absolute; left: 0px; top: 0px;">Canadian</div>


为什么会发生这种情况,我该如何解决?

0h4hbjxa

0h4hbjxa1#

试试这种方法,也许会对你有帮助

$html_output = '<div class="element-item ' . $term . '">';
echo $html_output;

字符串

cbwuti44

cbwuti442#

试着这样

echo "<div class="element-item $term>";

字符串

你可以在JavaScript的帮助下这样做

$(function(){
   $('.element-item').addClass('<?php echo $term ?>');
   });


如果你有什么问题,

gwbalxhn

gwbalxhn3#

您已经正确地识别了返回值方面的问题。
问题在这里:

$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

相关问题