Wordpress:如何通过slug(类别名称)在特定类别中搜索

时间:2016-06-18 16:20:35

标签: wordpress

如何创建一个代码,通过slug(类别名称)搜索,而不是按ID搜索。如何为我的客户端创建自定义解决方案,以便在特定类别(没有任何插件)中进行搜索?

解释:我希望自定义搜索代码,使客户端可以在特定类别中搜索而无需编辑任何代码。谢谢!

1 个答案:

答案 0 :(得分:1)

实际上,你应该检查this tutorial作者提供有关搜索功能自定义的详细说明。

您需要的最有趣的部分之一:

// meta_query expects nested arrays even if you only have one query
$sm_query = new WP_Query( array( 'post_type' => 'accommodation', 'posts_per_page' => '-1', 'meta_query' => array( array( 'key' => '_sm_accommodation_city' ) ) ) );

// The Loop
if ( $sm_query->have_posts() ) {
    $cities = array();
    while ( $sm_query->have_posts() ) {
        $sm_query->the_post();
        $city = get_post_meta( get_the_ID(), '_sm_accommodation_city', true );

        // populate an array of all occurrences (non duplicated)
        if( !in_array( $city, $cities ) ){
            $cities[] = $city;    
        }
    }
}
} else{
       echo 'No accommodations yet!';
       return;
}


/* Restore original Post Data */
wp_reset_postdata();

if( count($cities) == 0){
    return;
}

asort($cities);

$select_city = '<select name="city" style="width: 100%">';
$select_city .= '<option value="" selected="selected">' . __( 'Select city', 'smashing_plugin' ) . '</option>';
foreach ($cities as $city ) {
    $select_city .= '<option value="' . $city . '">' . $city . '</option>';
}
$select_city .= '</select>' . "\n";

reset($cities);