Page 1 of 1

Search Wordpress Custom Types & Group From Normal Post

Posted: Wed Dec 12, 2018 1:40 am
by kachan64
So I had a custom plugin that allows you to create custom taxonomy/post type like audio which can be used for audio library in conjunction with ACF which allows you to input data into the library and have a custom archive and a post template that style the looks. But was out of luck when comes to searching them.

Luckily below code serves that purpose by adding custom post type into the main search results. Add to your functions.php.

Code: Select all

add_filter( 'pre_get_posts', 'tgm_io_cpt_search' );
/**
 * This function modifies the main WordPress query to include an array of 
 * post types instead of the default 'post' post type.
 *
 * @param object $query  The original query.
 * @return object $query The amended query.
 */
function tgm_io_cpt_search( $query ) {
	
    if ( $query->is_search ) {
	$query->set( 'post_type', array( 'post', 'audios') );
    }
    
    return $query;
    
}
But however it uses the same style as a normal post and it doesn't look good when you want to differentiate results like (https://www.exophase.com/search?s=Battlefield).

While a post at Stackoverflow ,ay actually solve my problem by creating a if condition inside my while have post loop.

Code: Select all

you can go through below code, just edit with your post types:

<?php while ( have_posts() ) : the_post(); ?>
<li>
    <?php
    if ($post->post_type == "cards") {
       //do fancy things


    }
    if ($post->post_type == "mycards") {
       //do fancy things


    }
    else {
       //otherwise just sit
    }

    <article>
        <h2><a href="<?php esc_url( the_permalink() ); ?>" title="Permalink to <?php the_title(); ?>" rel="bookmark"><?php the_title(); ?></a></h2>
        <time datetime="<?php the_time( 'Y-m-d' ); ?>" pubdate><?php the_date(); ?> <?php the_time(); ?></time> <?php comments_popup_link('Leave a Comment', '1 Comment', '% Comments'); ?>
        <?php the_content(); ?>
    </article>
    ?>

</li>
You will need to modify a few things to have it structed like below:
if have post
- if post type
CODE FOR CUSTOM POST TYPE RESULT
- else
CODE FOR NORMAL SEARCH RESULT
- end if
- else
ERROR MESSAGE FOR NO RESULTS
- end if
And that's it! Now your custom post type results won't be like regular post type results.

:P

Re: Search Wordpress Custom Types & Group From Normal Post

Posted: Mon Apr 22, 2019 3:47 pm
by priyanshu
Really great information related to web design

Re: Search Wordpress Custom Types & Group From Normal Post

Posted: Fri Jun 28, 2019 2:54 pm
by Pallavipatil
Excellent information here...Thanks for this post...Keep up!