I am trying to build upon and enhance the default wordpress search so that you can search pages and custom post type meta data as well. It works great, except custom field titles are not being output. I do print_r($custom_fields);
and it shows that the values are stored. I am just lost on what I am missing, but I think it has to do with the two foreach loops skipping over the first values?
Here are images showing what is happening and the code:
Result if searching: See how Parkmerced (first paragraph):
Result if searching: we’ve brought together (second paragraph):
functions.php (functions related to search)
function cf_search_join( $join ) {
global $wpdb;
if ( is_search() ) {
$join .=' LEFT JOIN '.$wpdb->postmeta. ' ON '. $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id ';
}
return $join;
}
add_filter('posts_join', 'cf_search_join' );
function cf_search_where( $where ) {
global $pagenow, $wpdb;
if ( is_search() ) {
$where = preg_replace(
"/(s*".$wpdb->posts.".post_titles+LIKEs*('[^']+')s*)/",
"(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->postmeta.".meta_value LIKE $1)", $where );
}
return $where;
}
add_filter( 'posts_where', 'cf_search_where' );
function cf_search_distinct( $where ) {
global $wpdb;
if ( is_search() ) {
return "DISTINCT";
}
return $where;
}
add_filter( 'posts_distinct', 'cf_search_distinct' );
search.php
<?php if ( have_posts() ) : ?>
<section class="search-results">
<p class='show-results'><?php printf( __( 'Showing search results for: <span>%s', 'parkmerced-vision' ), get_search_query() ); ?></span></p>
<?php while ( have_posts() ) : the_post(); ?>
<!-- something found -->
<div class="result animated fade-in-up delay-<?php echo $i; ?>">
<a href="<?php the_permalink(); ?>"><h4><?php the_title(); ?></h4></a>
<?php
the_excerpt();
$searched = get_search_query();
$custom_fields = get_post_custom();
foreach($custom_fields as $field_key => $field_values) {
foreach($field_values as $key => $value) {
if(stripos($value, $searched)) {
$in = $value;
$search = $searched;
$replace = '<strong>' . $searched . '</strong>';
$out = str_ireplace($search, $replace, $in);
echo '<p>' . $out . '</p>';
}
}
}
?>
</div>
<?php endwhile; else : ?>
<!-- nothing found -->
<h2>Nothing Found</h2>
<div class="alert alert-info">
<p>Sorry, but nothing matched your search criteria. Please try again with some different keywords.</p>
</div>
<a class="search-back btn" href="<?php echo home_url('/'); ?>/faq">return to faq</a>
<?php endif; ?>
</section>
<?php get_footer(); ?>
The issue wasn’t with the post data, but with the output of the values themselves. The arrays were connected together causing the first words of all strings to be attached to the previous array values: