2017-07-27 74 views
0

我想僅根據頁面和帖子標題進行搜索。可能嗎? 在頭文件搜索代碼低於如何僅在wordpress中搜索帖子和頁面標題?

<form method="get" class="search-form" action="<?php echo esc_url(home_url('/')); ?>"> 
    <input type="search" class="form-control" placeholder="<?php esc_attr_e('Search...', 'consulting'); ?>" value="<?php echo esc_attr(get_search_query()); ?>" name="s" /></div> 
    <button type="submit" style="height:7.5vh;"><i class="fa fa-search"></i></button> 
</form> 
+0

這將取決於'get_search_query()'函數,它在搜索什麼我會想象 –

+0

這是WordPress的搜索,請幫我找只標題 –

+0

ü意味着這個? https://wordpress.stackexchange.com/questions/96369/search-post-title-only – Hash

回答

0

可以在職位和頁面標題搜索,請添加以下代碼的functions.php

function __search_by_title_only($search, &$wp_query) 
{ 
    global $wpdb; 
    if(empty($search)) { 
     return $search; // skip processing - no search term in query 
    } 
    $q = $wp_query->query_vars; 
    $n = !empty($q['exact']) ? '' : '%'; 
    $search = ''; // this must be empty first 
    $searchand = ''; 
    foreach ((array)$q['search_terms'] as $term) { 
     $term = esc_sql($wpdb->esc_like($term)); 
     $search .= "{$searchand}($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')"; 
     $searchand = ' AND '; 
    } 
    if (!empty($search)) { 
     $search = " AND ({$search}) "; 
     if (!is_user_logged_in()) 
     $search .= " AND ($wpdb->posts.post_password = '') "; 
    } 
    return $search; 
} 
add_filter('posts_search', '__search_by_title_only', 500, 2); 
+0

我嘗試這個代碼,但它不工作。仍然顯示標題和描述。我只想顯示標題。 –

+0

以下代碼在標題中搜索,如果您想在搜索結果中顯示標題。你必須建立一個搜索頁面(search.php),見https://codex.wordpress.org/Creating_a_Search_Page @Anilbhadula – mshomali

+0

沒有辦法獲得標題搜索結果。如果我不會創建新的搜索模板,請告訴我另一種搜索方式 –

0
function __search_by_title_only($search, &$wp_query){ 

    global $wpdb; 

    if(empty($search)) { 

    return $search; // skip processing - no search term in query 

    } 

    $q = $wp_query->query_vars; 

    $n = !empty($q['exact']) ? '' : '%'; 

    $search = ''; 

    $searchand = ''; 

    foreach ((array)$q['search_terms'] as $term) { 

    $term = esc_sql($wpdb->esc_like($term)); 

    $search .= "{$searchand}($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')"; 

    $searchand = ' AND '; 

} 

    if (!empty($search)) { 

    $search = " AND ({$search}) "; 

    if (!is_user_logged_in()) 
     $search .= " AND ($wpdb->posts.post_password = '') "; 

} 

    return $search; 

} 

    add_filter('posts_search', '__search_by_title_only', 500, 2); 

在添加此代碼的主題functions.php文件

0

在search.php中使用以下查詢來覆蓋默認搜索功能或者您可以使用自定義模板

$args = array(
      'post_type' => 'post', 
      's' => $keyword, 
      'cat' => $catSearchID, 
      'tag' => $tag-slug, 
      'posts_per_page' => -1, 
      'location' => $post_location_search , 
     ); 

$wp_query = new WP_Query($args); 
+0

在wordpress有searchform.php,所以在查詢執行開始之前,把代碼 –

+0

。 – GNANA

相關問題