WordPress.org

Ready to get started?Download WordPress

Forums

[How-To] (1 post)

  1. The Love of Code
    Member
    Posted 2 years ago #

    I saw a number of posts asking how to make search only return posts, and not pages or other post types. The most common reply said to check $post->post_type inside the loop, and continue; if the post type is anything but 'post'. The problem with this is that it leads to odd behavior when functions like have_posts() are used.

    Instead, place this code above get_header() in search.php

    ## Only Posts
    global $wp_query;
    $wp_query = new WP_Query(array_merge($wp_query->query_vars, array(
    	'post_type' => 'post'
    )));

    That will take whatever the existing query variable for the current search are, and will simply override the post_type to be 'post'. (You can also use this to do things like prevent search from returning private posts.)

    - The Love of Code

Topic Closed

This topic has been closed to new replies.

About this Topic

  • RSS feed for this topic
  • Started 2 years ago by The Love of Code
  • This topic is not resolved
  • WordPress version: 3.3.1