SearchWP

searchwp\post_stati

Since: 4.0.0

Table of Contents

Control the considered post stati for \WP_Post-based Sources.

Note that in order for this hook to properly take effect you must understand how SearchWP’s Index works. The Index represents the ‘maximum’ pool of potential results, and Queries are run against that Index to limit the entries returned.

That said, in order to customize which post stati are returned in results we need to follow a two step process:

  1. Broaden the Index to contain all applicable post stati
  2. Hook in to the Queries to ensure only our expected post stati are returned

? Proceed with caution as improper use of this hook can expose data!

Parameters

Type Parameter Default Since
String[] $post_stati Post stati that are public and not excluded from search 4.0.0
Array $args
Key Type Value
engine String Engine name
4.0.0

Examples

All hooks should be added to your custom SearchWP Customizations Plugin.

Include drafts in Supplemental Engine

<?php
/**
* Include Drafts in SearchWP Supplemental Engine results.
*
* NOTE: In order for this to work we need to first tell SearchWP to index
* ALL of the potential post stati. We can then curate which post stati
* to consider during searches; it is a two-step process.
*/
// Step 1: tell SearchWP to index Drafts in addition to its default post stati.
add_filter( 'searchwp\post_stati', function( $post_stati, $args ) {
$post_stati[] = 'draft';
return $post_stati;
}, 20, 2 );
// Step 2: limit post stati during searches, per post type. By default
// SearchWP is going to respect the stati we defined in Step 1!
add_filter( 'searchwp\query\mods', function( $mods, $query ) {
// If this is the 'supplemental' Engine, search all post stati.
if ( 'supplemental' === $query->get_engine()->get_name() ) {
return $mods;
}
// Only return WP_Posts with 'publish' post status.
foreach ( $query->get_engine()->get_sources() as $source ) {
$flag = 'post' . SEARCHWP_SEPARATOR;
if ( 'post.' !== substr( $source->get_name(), 0, strlen( $flag ) ) ) {
continue;
}
$mod = new \SearchWP\Mod( $source );
$mod->set_where( [ [
'column' => 'post_status',
'value' => [ 'publish' ],
'compare' => 'IN',
] ] );
$mods[] = $mod;
}
return $mods;
}, 20, 2 );

How to use this code