News, Tutorials, Wordpress

How to change search results content or get content for custom fields search

21 November 2017

First of all add Search Everything plugin and set custom fields search.
Then go to you current theme in WordPress and open this file “search.php”.
In “search.php” file one can see code as below:

<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>

<?php the_excerpt(); ?>

So by default only Title or Content of page or post will be displayed in search results. But in some cases if suppose there is no content in page or post then it will only show title in the search result which will be looking weird in between other search results.

Here Search function is searching the string in custom fields and that’s why that particular search result appear. If suppose you want to display some content line for it then we can do it but adding below code and calling below mentioned function.

<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>

<?php if ( !empty( get_the_content() ) ) { the_excerpt(); } else { $pid = get_the_ID(); $pmeta = get_post_meta($pid); marray($pmeta, $_GET['s']); } ?>
function marray($arry, $str) {
  foreach ($arry as $key => $value) {
    if (is_array($value)) {
      marray($value, $str);
    } else {
      if (stripos($value, $str) !== false) {
        echo '
        ' . $value . '

The above code will check whether content is null or not while rendering the search results page. So if the content will be there then it will display simple content but if content will be null then it means the search engine have found search string in some custom fields, above code will check in custom field of that post and get content of that custom field which you can display as content of that particular search result. Now all the search results will be displayed properly with same elements of title and content. so the search results will look uniformed and beautiful.

Leave a Comments