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);

Wie Forge12 mit solchen Themen arbeitet

Forge12 betreibt und ver­ant­wor­tet umsatz­kri­ti­sche Word­Press- und Woo­Com­mer­ce-Sys­te­me im lau­fen­den Betrieb. Bevor wir Sys­te­me über­neh­men oder wei­ter­ent­wi­ckeln, ana­ly­sie­ren wir sie voll­stän­dig – tech­nisch, struk­tu­rell und betrieb­lich. Das Sys­tem Audit ist der Ein­stiegs­punkt für jede Zusam­men­ar­beit.

88e86fcb816eff22bc917094df2862d8dd5c0e978b333e6dd5f36f808990c261 96

Arti­kel von:

Marc Wag­ner

Marc Wag­ner ist Grün­der der Forge12 Inter­ac­ti­ve GmbH und ver­ant­wort­lich für Betrieb, Absi­che­rung und Wei­ter­ent­wick­lung umsatz­kri­ti­scher Word­Press- und Woo­Com­mer­ce-Sys­te­me.

Seit über 20 Jah­ren arbei­tet er an Web­sites, Online-Shops und indi­vi­du­el­len Soft­ware­lö­sun­gen – vom Mit­tel­stand bis zu Struk­tu­ren bör­sen­no­tier­ter Unter­neh­men. Sein Fokus liegt nicht auf Pro­jek­ten, son­dern auf dau­er­haf­tem Betrieb: sta­bi­le Sys­te­me, kla­re Ver­ant­wort­lich­kei­ten und tech­ni­sche Ent­schei­dun­gen mit wirt­schaft­li­cher Kon­se­quenz.

Bei Forge12 beglei­tet er Unter­neh­men, die ihre Sys­te­me nicht nur bau­en, son­dern lang­fris­tig sicher betrei­ben und auto­ma­ti­sie­ren wol­len.

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