Skip to content

Instantly share code, notes, and snippets.

@felipeelia
Created December 8, 2022 18:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felipeelia/ddea93b887d905cadabf7f6211f5c54a to your computer and use it in GitHub Desktop.
Save felipeelia/ddea93b887d905cadabf7f6211f5c54a to your computer and use it in GitHub Desktop.
[ElasticPress] Sync and search for Media (attachment) posts in WordPress
<?php
/**
* Sync and search for Media (attachment) posts in WordPress.
* It is NOT to be used with the ElasticPress's Documents feature
*/
/**
* Add the attachment post type to be indexable and searchable
*
* @param array $post_types Post types
* @return array
*/
function ep_3189_add_attachment( $post_types ) {
$post_types['attachment'] = 'attachment';
return $post_types;
}
add_filter( 'ep_indexable_post_types', 'ep_3189_add_attachment' );
add_filter( 'ep_searchable_post_types', 'ep_3189_add_attachment' );
/**
* Add the `inherit` post status to a search query, so it can also find attachments
*
* @param WP_Query $query The WP Query object
*/
function ep_3189_add_inherit_to_search_query( $query ) {
$s = $query->get( 's', false );
if ( empty( $s ) ) {
return;
}
$post_type = $query->get( 'post_type', [] );
if ( ! empty( $post_type ) ) {
if ( 'any' !== $post_type ) {
if ( is_string( $post_type ) ) {
$post_type = explode( ' ', $post_type );
$post_type[] = 'attachment';
$query->set( 'post_type', array_unique( $post_type ) );
}
}
}
if ( empty( $post_status ) ) {
$post_status = array_values(
get_post_stati(
[
'public' => true,
'exclude_from_search' => false,
]
)
);
// Add inherit for documents
$post_status[] = 'inherit';
} else {
if ( is_string( $post_status ) ) {
$post_status = explode( ' ', $post_status );
}
$post_status[] = 'inherit';
}
$query->set( 'post_status', array_unique( $post_status ) );
}
add_action( 'pre_get_posts', 'ep_3189_add_inherit_to_search_query' );
/**
* Add the `inherit` post status to be indexed
*
* @param array $statuses Indexable post stati
* @return array
*/
function ep_3189_indexable_post_status( $statuses ) {
if ( ! array_search( 'inherit', $statuses, true ) ) {
$statuses[] = 'inherit';
}
return $statuses;
}
add_filter( 'ep_indexable_post_status', 'ep_3189_indexable_post_status' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment