gpt4 book ai didi

ajax - 如何仅在帖子标题中搜索 - wp_query

转载 作者:行者123 更新时间:2023-12-05 08:30:50 26 4
gpt4 key购买 nike

我在帖子过滤器表单中添加了一个文本字段,并使用 s= 参数来进行搜索。但是如何只在帖子的标题中搜索(而不是在内容中)?

HTML:

<input type="text" name="search" placeholder="Search..." value="">
<button>Filter</button>

PHP:

    $args = array(
'post_type' => $_POST['posttype'],
'orderby' => $_POST['orderby'],
'order' => $_POST['order'],
's' => $_POST['search']
);

最佳答案

Locate the file you need the search function implemented on and add the code below to your file.

$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'orderby' => $_POST['orderby'],
'order' => $_POST['order'],
'search_prod_title' => $_POST['search'],
);
add_filter( 'posts_where', 'title_filter', 10, 2 );
$query = new WP_Query($args);
remove_filter( 'posts_where', 'title_filter', 10, 2 );

To search title in your WordPress query, you need to add a function to your WordPress theme’s functions.php file.

版本 3.9

function title_filter( $where, &$wp_query ){
global $wpdb;
if ( $search_term = $wp_query->get( 'search_prod_title' ) ) {
$where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql( like_escape( $search_term ) ) . '%\'';
}
return $where;
}

弃用 4.0.0 使用 wpdb::esc_like() https://make.wordpress.org/core/2014/06/20/like_escape-is-deprecated-in-wordpress-4-0/

function title_filter( $where, &$wp_query ){
global $wpdb;
if ( $search_term = $wp_query->get( 'search_prod_title' ) ) {
$where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql( $wpdb->esc_like( $search_term ) ) . '%\'';
}
return $where;
}

关于ajax - 如何仅在帖子标题中搜索 - wp_query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62350261/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com