Wie kann ich in WordPress die Suche um eigene Post Types erweitern? (Anleitung, 2023)

Marc Wag­ner

Janu­ar 24, 2023

4 min read|

Stan­dard­mä­ßig wer­den eige­ne Post Types (Cus­tom Post Types) nicht in der Word­Press Suche berück­sich­tigt. Aber wie immer bei Word­Press gibt es auch hier einen Hook, mit dem wir jetzt gleich die Suche erweitern/anpassen. Im Hand­um­dre­hen hast du die Suche ange­passt.

So erweiterst du die WordPress Suche mit PHP um Custom Post Types #

Den Hook den wir für die Erwei­te­rung der Suche benö­ti­gen, lau­tet pre_get_posts. Im Fol­gen­den zei­ge ich dir ver­schie­de­ne Snip­pets, die dei­ne Suche anpas­sen wer­den.

Code Snippet für PHP 8

Falls auf dei­nem Ser­ver bereits PHP 8 unter­stützt wird, emp­feh­len wir dir fol­gen­des Snip­pet, um dei­ne Suche anzu­pas­sen:

/**
 * This function extends the default WordPress WP_Query object 
 * to include an array of post types instead of the default 'post'
 * post type.
 */
function add_post_types_to_search_query(WP_Query $query): void{
  // Skip if this call has been triggered for an administrative interface page.
  if(is_admin()){
    return;
  }
  
  // Skip this call if this is not the search query and if this is not the main query.
  if(!$query->is_search() || !$query->is_main_query()){
    return;
  }
  
  // Define which post types should be searched
  $list_of_post_types = ['post', 'pages'];
  
  // Now - if we get to this point, this must be the search query which we will modify.
  $query->set('post_type', $list_of_post_types);
}
add_action('pre_get_posts', 'add_post_types_to_search_query', 10, 1);

Alternative: Code Snippet für PHP 7

Die­sen Code soll­test du nur ver­wen­den, wenn PHP 8 noch nicht auf dei­nem Ser­ver läuft bzw. dei­ne Sei­te nicht mit PHP 8 kom­pa­ti­bel ist.

/**
 * This function extends the default WordPress WP_Query object 
 * to include an array of post types instead of the default 'post'
 * post type.
 */
function add_post_types_to_search_query($query){
  // Skip if this call has been triggered for an administrative interface page.
  if(is_admin()){
    return;
  }
  
  // Skip this call if this is not the search query and if this is not the main query.
  if(!$query->is_search() || !$query->is_main_query()){
    return;
  }
  
  // Define which post types should be searched. Replace/Extend by your post types.
  $list_of_post_types = array('post', 'pages');
  
  // Now - if we get to this point, this must be the search query which we will modify.
  $query->set('post_type', $list_of_post_types);
  
}
add_action('pre_get_posts', 'add_post_types_to_search_query', 10, 1);

Langfristiger einfach zu Pflegen dank OOP, Code Snippet

Hier ein Bei­spiel, wie du das Gan­ze mit einer Klas­se und Name­spaces abbil­den kannst, falls du lang­fris­tig den War­tungs­auf­wand gering hal­ten möch­test.

namespace My_Search{
  /**
   * This class extends the default WordPress WP_Query object
   * to include an array of post types instead of the default 'post'
   * post type.
   */
  class Search_Query_Post_Type_Modifier{
    /**
     * There should never be more than one object of this class therfor
     * we need to create a Singleton
     */
    private static ?Search_Query_Post_Type_Modifier $_instance = null;
    
    /**
     * This function will allow us to access the instance of this class
     */
    public static function get_instance(): Search_Query_Post_Type_Modifier{
        if(null === self::$_instance){
           self::$_instance = new Search_Query_Post_Type_Modifier();
        }
      
      	return self::$_instance;
    }
    
    /**
     * Private constructor to disable multiple instances of this object.
     */
    private function __construct(){
     	add_action('pre_get_posts', [$this, 'add_post_types_to_query']);
    }
    
    /**
     * Add the post types to the search query
     */
    public function add_post_types_to_query(WP_Query $query): void{
  		// Skip if this call has been triggered for an administrative interface page.
  		if(is_admin()){
           	return;
        }

        // Skip this call if this is not the search query and if this is not the main query.
        if(!$query->is_search() || !$query->is_main_query()){
          	return;
        }

        // Define which post types should be searched
        $list_of_post_types = ['post', 'pages'];

        // Now - if we get to this point, this must be the search query which we will modify.
        $query->set('post_type', $list_of_post_types);
  	}
  }
  
  /**
   * Instantiate the object
   */
  Search_Query_Post_Type_Modifier::get_instance();
}

Möglichst wenig Zeilen Code:

Die­se Ver­si­on ist dafür gedacht, ein­fach mög­lichst wenig Zei­len Code zu ver­wen­den :)

add_action('pre_get_posts', function(WP_Query $query){
   if(!is_admin() && $query->is_search() && $query->is_main_query()){
     $query->set('post_type', ['post','page']);
   }
}, 10, 1);
88e86fcb816eff22bc917094df2862d8dd5c0e978b333e6dd5f36f808990c261 96

Arti­kel von:

Marc Wag­ner

Hi Marc here. I’m the foun­der of Forge12 Inter­ac­ti­ve and have been pas­sio­na­te about buil­ding web­sites, online stores, appli­ca­ti­ons and SaaS solu­ti­ons for busi­nesses for over 20 years. Befo­re foun­ding the com­pa­ny, I alre­a­dy work­ed in publicly lis­ted com­pa­nies and acqui­red all kinds of know­ledge. Now I want to pass this know­ledge on to my cus­to­mers.

Hast du eine Fra­ge? Hin­ter­lass bit­te einen Kom­men­tar