簡體   English   中英

獲取具有類別名稱以術語開頭的帖子

[英]Get posts that have a category name begin by a term

如果我使用WP_Query類例如:

$query = new WP_Query( 'category_name=staff,news' );

我將使用類別標簽獲取具有這些類別的帖子,但是如何獲取具有類別名稱的帖子,例如,以術語開頭:

$query = new WP_Query( 'category_name=s%' );

我希望我能很好地解釋我的問題。 謝謝

您可以在主題functions.php中創建一個函數,如下所示:

<?php

/**
* @ $taxonomy = the taxonomy name 
* @ $search = the string you are searching
* @ return array of term names
*/
function getDesiredTerms($taxonomy, $search) {

    $result = get_terms(
        $taxonomy, 
        array(
            'hide_empty'    => false, // get them all           
            'fields'        => 'names', // get only the term names  
            'name__like'    => $search // Note: This was changed in WordPress 3.7, when previously name__like matched terms that begin with the string.
            )
        );
    return $result;

}

請注意您使用的是哪個Wordpress版本。

有關Codex的更多詳細信息,請參見http://codex.wordpress.org/Function_Reference/get_terms 尋找'name__like'參數

萬一有人偶然發現,我需要進行搜索,其中包括功能get_terms中的模糊匹配。 我最初使用name__like來幫助優化搜索結果,但最終得到了所有術語,並使用了similar_text()來比較搜索輸入與術語名稱。

下面是我最終使用的功能。 希望它能幫助某人:

$search_text = "WHATEVER YOUR SEARCH INPUT IS";

$args = array(
    'taxonomy'      => array( 'product_cat' ), // taxonomy name
    'orderby'       => 'id', 
    'order'         => 'ASC',
    'hide_empty'    => false,
    'fields'        => 'all'
    //'name__like'    => $search_text  //I TOOK THIS PART OUT
); 
$terms = get_terms( $args );

//FILTER FUZZY MATCHING
foreach($terms as $term) {
    $item = similar_text($search_text, $term->name, $percentage);
    if($percentage >= 50) :
        echo $term->name . ' - ' . $percentage . '<br />';
    endif; 
}

您可以修改百分比閾值以產生所需的結果。 就我而言,這對我來說非常有用。 在某些情況下,它對其他人可能效果不佳。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM