Skip to content

Instantly share code, notes, and snippets.

@jchristopher
Created February 20, 2018 14:30
Show Gist options
  • Save jchristopher/9028accde99ff01527664d293142ee0d to your computer and use it in GitHub Desktop.
Save jchristopher/9028accde99ff01527664d293142ee0d to your computer and use it in GitHub Desktop.
Programmatically override the Custom Fields for a SearchWP engine
<?php
class SwpProgrammaticCustomFields {
// These meta keys will be indexed and made searchable
private $meta_keys = array(
array(
'post_type' => 'post',
'meta_keys' => array(
array(
'metakey' => 'my_meta_key',
'weight' => 10,
),
array(
'metakey' => 'another_meta_key',
'weight' => 40,
),
),
),
);
function __construct() {
add_filter( 'searchwp_omit_meta_key', array( $this, 'whitelist_meta_key' ), 10, 3 );
add_filter( 'searchwp_engine_settings_default', array( $this, 'modify_engine_settings' ), 10, 2 );
}
/*
* Retrieves meta keys from $this->meta_keys based on post type
*/
function get_meta_keys_for_post_type( $post_type = 'post' ) {
if ( ! post_type_exists( $post_type ) ) {
return array();
}
$meta_keys = array();
foreach ( $this->meta_keys as $meta_keys ) {
if ( $post_type !== $meta_keys['post_type'] ) {
continue;
}
$meta_keys = wp_list_pluck( $meta_keys, 'metakey' );
break;
}
return $meta_keys;
}
/**
* Tell SearchWP to index our meta keys
*/
function whitelist_meta_key( $excluded, $meta_key, $post_being_indexed ) {
return ! in_array( $meta_key, $this->get_meta_keys_for_post_type( $post_being_indexed->post_type ) );
}
/*
* Replace engine Custom Fields with our $meta_keys
*/
function modify_engine_settings( $settings, $query ) {
foreach ( $this->meta_keys as $meta_keys ) {
if ( ! isset( $settings[ $meta_keys['post_type'] ]['weights'] ) ) {
continue;
}
$settings[ $meta_keys['post_type'] ]['weights']['cf'] = $meta_keys['meta_keys'];
}
return $settings;
}
}
new SwpProgrammaticCustomFields();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment