0

UPDATED:

I have a Custom Post Type Commercials. This post type has a title and a video id. I want to search from this specific post type. Right now it returns result which matches the titles only, I also want it to return result from tags too. For example, let's say I have a commercial named "Lorem Ipsum Commercial" and this has a tag my tag. I want to it to return result if the searched value matches the title or the tag. This is as far I got.

function.php

function searchCommercial($query) {
  if ( $query -> is_search && !is_admin() ) {
    if( isset($_GET['post_type']) ) {
      $type = $_GET['post_type'];
      if( $type == 'commercials' ) {
        $query -> set( 'post_type', array('commercials') );
        /*
        $terms = explode(' ', $query->get('s'));
        $query->set('tax_query', array(
            'relation'=>'OR',
            array(
                'taxonomy'=>'post_tag',
                'field'=>'slug',
                'terms'=>$terms
            )
        ));*/
      }
    }
  }
  return $query;
}

add_filter( 'pre_get_posts', 'searchCommercial' );

Search form:

<form role="search" method="GET" class="search-form" action="<?php echo home_url('/'); ?>">
  <label>
    <input type="search" class="search-field" name="s" value="<?php echo get_search_query(); ?>" >
    <input type="hidden" name="post_type" value="commercials">
  </label>
  <input type="submit" class="submit" value="Search">
</form>

search.php

if ( have_posts() ) :
  while ( have_posts() ) : the_post();
    if ( isset($_GET['post_type']) ) {
      $type = $_GET['post_type'];
      if ( $type == 'commercials' ) {
        get_template_part( 'templates/content-commercilas' );
      }
    }
  endwhile;
endif;

I've been trying to solve this for two days, any help would be very much appreciated.

UPDATE post type codes

add_action('init', registering_commercial);
function registering_commercial() {
  $labels = array(
        'name'               => __( 'Commercials' ),
        'singular_name'      => __( 'Commercial' ),
        'menu_name'          => __( 'Commercials' ),
        'name_admin_bar'     => __( 'Commercial' ),
        'add_new'            => __( 'Add New' ),
        'add_new_item'       => __( 'Add New Commercial' ),
        'new_item'           => __( 'New Commercial' ),
        'edit_item'          => __( 'Edit Commercial' ),
        'view_item'          => __( 'View Commercial' ),
        'view_items'         => __( 'View Commercials' ),
        'all_items'          => __( 'All Commercials' ),
        'search_items'       => __( 'Search Commercial' ),
        'parent_item_colon'  => __( 'Parent Commercial:' ),
        'not_found'          => __( 'No Commercial found.' ),
        'not_found_in_trash' => __( 'No Commercial found in Trash.' ),
    'item_published'     => __( 'Commercial is published.' ),
    'item_updated'       => __( 'Commercial successfully updated!' )
    );

    $args = array(
        'labels'             => $labels,
        'description'        => __( 'Description for Commercials.' ),
        'public'             => true,
        'publicly_queryable' => true,
        'show_ui'            => true,
        'show_in_menu'       => true,
        'query_var'          => true,
        'rewrite'            => array( 'slug' => 'commercials' ),
        'capability_type'    => 'post',
        'has_archive'        => true,
        'hierarchical'       => false,
        'menu_position'      => null,
        'supports'           => array( 'title', 'thumbnail' ),
    'taxonomies'         => array( 'commercial_category', 'post_tag' )
    );

  register_post_type( 'commercials', $args );
}

Category Codes:

add_action( 'init', 'create_commercial_category', 0 );

function create_commercial_category() {
    $labels = array(
        'name'              => __( 'Commercial Categories' ),
        'singular_name'     => __( 'Category' ),
        'search_items'      => __( 'Search Category' ),
        'all_items'         => __( 'All Categories' ),
        'parent_item'       => __( 'Parent Category' ),
        'parent_item_colon' => __( 'Parent Category:' ),
        'edit_item'         => __( 'Edit Category' ),
        'update_item'       => __( 'Update Category' ),
        'add_new_item'      => __( 'Add New Category' ),
        'new_item_name'     => __( 'New Category Name' ),
        'menu_name'         => __( 'Commercial Category' ),
    );

    $args = array(
        'hierarchical'      => true,
        'labels'            => $labels,
        'show_ui'           => true,
        'show_admin_column' => true,
        'query_var'         => true,
        'rewrite'           => array( 'slug' => 'commercial-category' )
    );
    register_taxonomy( 'commercial_category', array( 'commercials' ), $args );
}
0

I think you need to remove

$_GET['post_type']

Please use below code i think you might help :

add_action( 'pre_get_posts', function ( $q )
{
    if (    !is_admin()         // Only target front end,
         && $q->is_main_query() // Only target the main query
         && $q->is_search()     // Only target the search page
    ) {
        $q->set( 'post_type', ['commercials'] );

        $terms = explode(' ', $q->get('s'));

        $q->set('tax_query', array(
            'relation'=>'OR',
            array(
                'taxonomy'=>'post_tag',
                'field'=>'slug',
                'terms'=>$terms
            )
        ));
    }
});
  • thank you for the answer, but it's still now working. I've attached the post type registering codes. Is there any change needs to be done there? – Muhammad Russell May 29 at 15:17
0

The way you are customizing the query you are telling it to search for posts that ALSO match a custom tax_query criteria. This would never work, logically speaking.

You said, "I want it to return a result if this tag is searched or if it matches the title" for which I understand ONE or ANOTHER.

I'll show you a completely different approach, using basically the following logic:

  1. You said "This post type has a title and a video id" so I assume you are not going to use the field/column post_excerpt for the CPT commercials. You can add it to supports, but it is not required for this to work.
  2. We can make use of the action save_post to force WordPress adding your post tags to the field post_excerpt of a Commercial. When you take a look at the code this will sound less confusing.
  3. We know that WordPress by default searches the columns post_title, post_excerpt and post_content for a term when the query var s is present. So doing number 2 above would solve your issue, because WordPress would take care of the rest.

Getting our hands dirty... we will still need to use the pre_get_posts action (yes, not a filter):

/**
 * @param WP_Query $query
 */
function searchCommercial( $query ) {
    if ( is_search() && ! is_admin() ) {
        if ( isset( $_GET['post_type'] ) ) {
            $type = $_GET['post_type'];
            if ( $type == 'commercials' ) {
                $query->set( 'post_type', array( 'commercials' ) );
            }
        }
    }
}

add_action( 'pre_get_posts', 'searchCommercial' );

And for saving the post tags within the post_excerpt of a Commercial:

/**
 * Fires once a post has been created or updated.
 *
 * @param int     $post_id
 * @param WP_Post $post
 * @param bool    $update Whether this is an existing post being updated or not.
 */
function add_post_tags_to_commercials( $post_id, $post, $update ) {
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return;
    }

    if ( wp_is_post_revision( $post_id ) ) {
        return;
    }

    if ( $post->post_type != 'commercials' ) {
        return;
    }

    $post_tags = wp_get_object_terms( $post_id, 'post_tag' );

    if ( $post_tags ) {
        $tags_with_comma = [];

        /**
         * @var WP_Term $tag
         */
        foreach ( $post_tags as $tag ) {
            $tags_with_comma[] = $tag->name;
            $tags_with_comma[] = $tag->slug;
        }

        $tags_with_comma = implode( ',', $tags_with_comma );

        // Unhook this function so it doesn't loop infinitely.
        remove_action( 'save_post', 'add_post_tags_to_commercials', 20 );

        wp_update_post(
            array(
                'ID'           => $post_id,
                'post_excerpt' => $tags_with_comma, // The tags will be saved within the `post_excerpt` column.
            )
        );

        // Re-hook this function.
        add_action( 'save_post', 'add_post_tags_to_commercials', 20, 3 );
    }
}

add_action( 'save_post', 'add_post_tags_to_commercials', 20, 3 );

The 2 snippets above can be placed within your functions.php file.

Notice:

  • If you are using Guttenberg for your CPT commercials, you may have issues attaching post tags to it. Until now, WP version 5.2.1, is still having trouble attaching tags to a post using the AJAX process.
  • You have to save all of your Commercials again. I hope it's just a few.
  • Consider adding the string excerpt to your commercials supports as it would make it easier for you to see what's been added to the post_excerpt column:
'supports'           => array( 'title', 'thumbnail', `excerpt` ),
  • Thank you so much for this elaborated answer. This will be an interesting way of solving the issue. I'll keep this one in mind, I would upvote your answer, but I do not have enough reputation for upvote. If I cannot find a better method I will accept this as the answer. – Muhammad Russell May 29 at 19:33

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.