wp query by search in titles only & put the posts in loop

The question:

i need to get posts by search in posts title only not search in full post & put the posts in loop to show it in a slider

Note : i need to get posts by keyword in title & put it in loop to showing it, not limiting search in all of the site

i used wp_query to do that but it is get posts by searching in full post “content&title”

 <?php $query = new WP_Query( 's=mykeyword&cat=22,32&order=dsc&showposts=6' ); ?>
 <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
 <p><?php the_title(); ?></p>
 <?php endwhile; ?>
 <?php endif; ?>

how can i do that

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

If you want to limit the filter from this answer (add that function to your plugin or your theme’s functions.php) just to one query, remove the filter when you are done:

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

$query = new WP_Query(
    array(
        's'         => 'mykeyword myotherkeyword',
        'cat'       => array( 22, 32 ),
        'orders'    => 'DESC',
        'showposts' => 6
    )
);

remove_filter( 'posts_search', '__search_by_title_only', 500 );

if ( $query->have_posts() ) :
    while ( $query->have_posts() ) :
        $query->the_post();
        the_title( '<p>', '</p>' );
    endwhile;

    wp_reset_postdata();
endif;


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment