2017-01-25 19 views
0

在WordPress的PHP工作我想傳遞一個值到一個元素中的類標籤問題有上傳遞變量轉換成HTML類標籤在WordPress中

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

該值正在從類標記中消失並顯示在頁面上!

enter image description here

我檢查的源代碼,似乎我傳遞整個的鏈接類的標籤!

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

請問我爲什麼會發生這種情況,我該如何解決?

+0

您是否閱讀過'get_the_term_list'描述? –

+0

我知道這會返回一個鏈接,但我怎麼才能得到slu??沒有鏈接? – Behseini

+0

使用其他功能? –

回答

0

嘗試這種方式,可能是它會幫助你

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

謝謝Nahid,但價值仍然是鏈接格式併發布出div! – Behseini

0

嘗試這樣

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


您可以用JavaScript的幫助,像這樣的

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

讓我知道你是否面臨任何問題

0

您已經根據返回值正確識別了問題。

問題就在這裏:

$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