Last active
April 6, 2022 19:33
-
-
Save felipeelia/2b48915c9f85b8a9b3149185ed4bbd40 to your computer and use it in GitHub Desktop.
Remove some meta fields from the ElasticPress/Elasticsearch index
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_filter( | |
'ep_prepare_meta_data', | |
function ( $prepared_meta ) { | |
foreach ( $prepared_meta as $key => $meta_val ) { | |
// Remove empty meta fields. | |
if ( empty( $key ) || empty( $meta_val ) || empty( $meta_val[0] ) ) { | |
unset( $prepared_meta[ $key ] ); | |
continue; | |
} | |
// Remove fields with key starting with "field_". | |
if ( 0 === strpos( $meta_val[0], 'field_' ) ) { | |
unset( $prepared_meta[ $key ] ); | |
continue; | |
} | |
// Remove fields with just letters, numbers, hyphens and underscores. | |
if ( '_sku' !== $key && preg_match( '/^([a-zA-Z0-9\-\_]*)$/', $meta_val[0] ) ) { | |
unset( $prepared_meta[ $key ] ); | |
continue; | |
} | |
} | |
return $prepared_meta; | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code is useful when you notice your content is not being fully indexed on ElasticPress/Elasticsearch. If you run
wp elasticpress index --setup --show-bulk-errors
and receive the following error
[illegal_argument_exception] Limit of total fields [5000] in index [<index_name>-post-1] has been exceeded
you need to reduce your meta fields number per post.
The code of this gist will remove all empty meta fields, fields with a value starting with "field_", and fields with a value containing only letters, numbers, hyphens, and underscores (probably just a code or hash).