search only in post titles in the wordpress to get

2019-09-07 21:06发布

问题:

I'm an android developer. I made a php file on my host and I include wp-blog-header.php . I used this file as a web service.

In the my app, there is a search part and I get term as String and category as id of user and send them to my php file .

now, I would like to search in post titles and return titles and ids of what user want.

function customSearch($term,$category){
.
.
.

}

I used prepare functions to get posts like below function, but I cannot find any function to search only in post titles.

function getLastItems()
{



    $args = array(
        'numberposts' => 5,
        'offset' => 0,
        'category' => 0,
        'orderby' => 'post_date',
        'order' => 'DESC',
        'post_type' => 'post',
        'post_status' => 'publish',
        'suppress_filters' => true );

    $recent_posts = wp_get_recent_posts( $args, ARRAY_A );

    $mjson = array();


    foreach( $recent_posts as $recent ){

        $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($recent['ID']), array(400,300) );
        $url_img = $thumb['0'];

        $marr = array(
            'id'=>$recent["ID"],
            'title'=>$recent["post_title"],
            'img'=>$url_img
        );

        array_push($mjson,$marr);

    }

    return  $mjson ;



}//end get last items

回答1:

I don't understand your search part, but your question about to search in only title , this answer will do for you.

  1. Add filter to search only in title, before search.
  2. Remove Filter after search.

if you want to search in title, just add below to args.

function search_by_title( $search, $wp_query ) {
    if ( ! empty( $search ) && ! empty( $wp_query->query_vars['search_terms'] ) ) {
        global $wpdb;

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

        $search = array();

        foreach ( ( array ) $q['search_terms'] as $term )
            $search[] = $wpdb->prepare( "$wpdb->posts.post_title LIKE %s", $n . $wpdb->esc_like( $term ) . $n );

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

        $search = ' AND ' . implode( ' AND ', $search );
    }

    return $search;
}


$args = array(
    's' => 'search string',
    'numberposts' => 5,
    'offset' => 0,
    'category' => 0,
    'orderby' => 'post_date',
    'order' => 'DESC',
    'post_type' => 'post',
    'post_status' => 'publish',
    'suppress_filters' => true);

add_filter( 'posts_search', 'search_by_title', 10, 2 );
$recent_posts = wp_get_recent_posts($args, ARRAY_A);
remove_filter( 'posts_search', 'search_by_title', 500 );


foreach($recent_posts as $posts) {

    // your custom code here
}


标签: php wordpress