Advertisement
Guest User

custom fields in relevanssi's search results

a guest
Jun 15th, 2011
324
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.15 KB | None | 0 0
  1. <?php
  2. /*
  3.  * Render the_content for the my post-type
  4.  */
  5. add_filter('the_content', 'my_the_content');
  6. function my_the_content($content) {
  7.  
  8.   //if the_content was triggered by relevanssi, we append the content of all relevant custom fields so that relevanssi includes their content (inlcuding the real my content if specified)
  9.   if($post = is_the_content_called_by_relevanssi()){
  10.    
  11.     // Fields to load content from
  12.     $fields = array('myfield1', 'myfield1');
  13.     foreach($fields as $field){
  14.       //pay attention to $single (http://codex.wordpress.org/Function_Reference/get_post_meta)
  15.       //die(print_r(get_post_meta($post->ID, $field, false), TRUE));
  16.       $content .= ' '. implode(' ', get_post_meta($post->ID, $field, TRUE));
  17.     }
  18.   }
  19.   else global $post;  //in general you want to use this $post object
  20.  
  21.   return $content;
  22. }
  23.  
  24. /*
  25.  * Check if the_content was triggered by relevanssi
  26.  *
  27.  * http://wordpress.org/support/topic/snippets-not-created-from-custom-fields?replies=11#post-2168264
  28.  */
  29. function is_the_content_called_by_relevanssi(){
  30.   //if relevanssi_init() does not exists, there is no relevanssi and relevanssi cannot have triggered the_contet
  31.   if(!function_exists('relevanssi_init')) return false;
  32.  
  33.   /*
  34.    * If we find a function call 'relevanssi_do_excerpt' in backtrace, the_content is triggered by relevanssis to create the excerpt from the_content
  35.    *
  36.    * expect not more than 10 the_content hooks
  37.    * 21 calculates as follows:
  38.    * apply_filters() + 10 * (call_user_func_array() + callbackfunction()) = 21
  39.    * you might want to increase this. Remember it slows down you script!
  40.    */
  41.   //limit trace depth if php version is newer than 5.4.0
  42.   if (strnatcmp(phpversion(),'5.4.0') >= 0)
  43.     $trace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 21);
  44.   else
  45.     $trace = debug_backtrace();
  46.   //search for relevanssi_do_excerpt() in backtrace
  47.   for($i = 0; $i<min(array(21,count($trace))); $i++){
  48.     //if we find relevanssi_do_excerpt in the stack return the $post object, which we need
  49.     if('relevanssi_do_excerpt' == $trace[$i]['function']) return $trace[$i]['args'][0];
  50.   }
  51.   return FALSE; //nothing found
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement