Skip to content

Instantly share code, notes, and snippets.

@5t3ph
Last active August 29, 2015 14:20
Show Gist options
  • Save 5t3ph/bfb404c45534291bc93d to your computer and use it in GitHub Desktop.
Save 5t3ph/bfb404c45534291bc93d to your computer and use it in GitHub Desktop.
WordPress: Customize CPT Search Results
/*
* For use when you have a custom page to display a custom post type but also need the CPT pulled into search results.
*
* Includes functions hooked to filters to alter the title, permalink, and excerpt.
* Uses switch statements for easily extending to additional custom post types.
*
*/
<?php
/**
* ADD POST TYPES TO SEARCH RESULTS
*/
function cpt_search_filter($query) {
if ( !is_admin() && $query->is_main_query() ) {
if ($query->is_search) {
$query->set('post_type', array( 'page', 'post', 'cpt' ) );
}
}
}
add_action('pre_get_posts', 'cpt_search_filter');
/**
* CHANGE SEARCH RESULT URL FOR CPTS TO LINK TO "PARENT"
*/
function cpt_search_permalinks($url) {
if(is_search()) {
$postid = url_to_postid( $url );
$post_type = get_post_type($postid);
$slug = get_post( $postid )->post_name;
switch ($post_type) {
case 'cpt':
return home_url('/parent/#'.$slug);
break;
default:
return $url;
}
} else {
return $url;
}
}
add_filter('the_permalink', 'cpt_search_permalinks');
/**
* PREPEND CPT SEARCH RESULT TITLE WITH "PARENT" PAGE
*/
function cpt_search_title($title, $postid) {
if(is_search()) {
$post_type = get_post_type($postid);
switch ($post_type) {
case 'cpt':
return 'Parent Title: '.$title;
break;
default:
return $title;
}
} else {
return $title;
}
}
add_filter('the_title', 'cpt_search_title', 10, 2);
/**
* UPDATE SEARCH RESULT FOR CPT TO USE CUSTOM FIELD VALUES
*/
function cpt_search_excerpt($excerpt) {
global $post;
$post_type = $post->post_type;
if(is_search()) {
switch ($post_type) {
case 'cpt':
$cpt_meta = get_post_meta($post->ID, 'cpt_meta', true);
return $cpt_meta;
break;
default:
return $excerpt;
}
} else {
return $excerpt;
}
}
add_filter('get_the_excerpt', 'cpt_search_excerpt');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment