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

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments