0

I have the searchform.php set up to search a custom post type and a category. So far so good. However, a savvy user could edit the URL to remove "post_type=film" and search all pages and posts.

I don't want it to do this! I'd essentially like the search hardcoded to only search the specific CPT regardless of what is in the URL slug. Is this possible?

search.php contains this:

<h1><?php echo sprintf( __( '%s Search Results for ', 'site' ), $wp_query->found_posts ); echo get_search_query(); ?></h1>

<?php get_template_part('loop'); ?>

<?php get_template_part('pagination'); ?>
2

I guess you mean overriding the post type of the main search query on the front-end. You could try:

add_action( 'pre_get_posts', function ( WP_Query $q )
{
    if ( 
            ! is_admin() 
         && $q->is_main_query() 
         && $q->is_search()
     )
        $q->set( 'post_type', 'film' );
} );

This way you don't need a secondary search query or mess directly with the globals.

0

Found a solution that should work with all themes.

function update_my_custom_type() {
global $wp_post_types;

if ( post_type_exists( 'post' ) ) {

    // exclude from search results
    $wp_post_types['post']->exclude_from_search = true;
}
}

Found it from http://www.webtipblog.com/exclude-custom-post-type-search-wordpress/

  • Not a very smart way unfortunately ;-) – Pieter Goosen Jan 18 '16 at 13:04
1

You can add another loop.php with a different name: loop-film.php and edit it's query so as to retrieve only the film post type. Afterwards in your search.php call on your new loop:

<h1><?php echo sprintf( __( '%s Search Results for ', 'site' ), $wp_query->found_posts ); echo get_search_query(); ?></h1>

    <?php get_template_part('loop-film'); ?>

    <?php get_template_part('pagination'); ?>

Also, I think you might need to duplicate pagination.php also and edit it. I don't know what files your theme has so this is only base on what you provided.

0

You can do this by editing the Search.php file in your theme.

This file will contain something along the lines of this:

<?php
global $query_string;

$query_args = explode("&", $query_string);
$search_query = array();

foreach($query_args as $key => $string) {
    $query_split = explode("=", $string);
    $search_query[$query_split[0]] = urldecode($query_split[1]);
} // foreach

$search = new WP_Query($search_query);
?>

If you add $search_query['post_type'] = 'film'; above of $search = new ... then the searchresults only contain items from the post_type "film".

  • Thanks but sadly my search.php contains something different. Please see edit. – tim daniels Jan 18 '16 at 11:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.