WordPress Development Asked by Sandeep Naskar on February 11, 2021
I want to search "sandwich"
I have
pages as "sandwich", sandwich-toast, sandwich-three-layer, sandwich-simple
posts as "sandwich-recipe", "sandwich-maker-links", "best-sandwich-in-newyork"
CPT as "sandwiches"
What is expected:
I want to search the keyword "sandwich". The expected result should be orderby my preference i.e
What I have tried so far:
<form method="get" id="searchform" action="" role="search" autocomplete="off">
<label class="sr-only" for="s"><?php esc_html_e( 'Search', 'understrap' ); ?></label>
<div class="input-group">
<input class="field form-control" id="s" name="s" type="text" autocomplete="off"
placeholder="<?php esc_attr_e( 'Search …', 'understrap' ); ?>" value="<?php the_search_query(); ?>">
<input type='hidden' name='post_type' value='' />
<span class="input-group-append">
<input class="submit btn btn-primary" id="searchsubmit" type="submit"
value="<?php esc_attr_e( 'Search', 'understrap' ); ?>">
</span>
</div>
</form>
while ( have_posts() ) : the_post();
if ('page' == get_post_type()) {
get_template_part( 'loop-templates/content', 'search' );
} else if('post' == get_post_type()) {
get_template_part( 'loop-templates/content', 'searchblog' );
} else if('sandwiches' == get_post_type()) {
get_template_part( 'loop-templates/content', 'searchcpt' );
} else {
get_template_part( 'loop-templates/content', 'search' );
}
endwhile;
add_filter( 'posts_orderby', 'order_search_by_posttype', 10, 2 );
function order_search_by_posttype( $orderby, $wp_query ){
if( ! $wp_query->is_admin && $wp_query->is_search ) :
global $wpdb;
$orderby =
"
CASE WHEN {$wpdb->prefix}posts.post_type = 'page' THEN '1'
WHEN {$wpdb->prefix}posts.post_type = 'post' THEN '2'
ELSE {$wpdb->prefix}posts.post_type END ASC,
{$wpdb->prefix}posts.post_title ASC";
endif;
return $orderby;
}
What I think is I need to add some sort of indexing to the pages, posts & custom post type so that I can decide the order the results should be displayed according to the priority I want to set them to display.
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP