Posted on

Envira Gallery

Envira Gallery is a gallery plugin for WordPress. Since it uses a custom post type for the galleries, it works fine with Relevanssi. However, the gallery post type doesn’t have any information about the actual images: no titles, tags or other details like that.

Since the images are uploaded in the Media Library and are attached to the gallery posts, this is easy to remedy using the very helpful relevanssi_content_to_index filter hook. Add the following code to your theme functions.php, set Relevanssi to index the envira post type and rebuild the index:

add_filter( 'relevanssi_content_to_index', 'rlv_envira_gallery_content', 10, 2 );
/**
 * Indexes the attachment content as part of the Envira Gallery posts.
 *
 * @param string  $content The post content.
 * @param WP_Post $post    The post object.
 *
 * @return string The updated content.
 */
function rlv_envira_gallery_content( string $content, WP_Post $post ) : string {
	if ( 'envira' !== $post->post_type ) {
		return $content; // Not a gallery post, skip.
	}
	$args     = array(
		'post_parent'    => $post->ID,
		'posts_per_page' => -1,
	);
	$children = get_children( $args ); // Fetches all the attached images.
	foreach ( $children as $child ) {
		$content .= ' ' . $child->post_title; // Adds the image title.
		$content .= ' ' . $child->post_excerpt; // Adds the image caption.

        $tags = get_the_terms( $child->ID, 'envira-tag' );
		if ( ! is_array( $tags ) ) {
			$tags = array();
		}
		foreach ( $tags as $tag ) {
			$content .= ' ' . $tag->name; // Adds the tag name.
		}
      
		$cats = get_the_terms( $child->ID, 'envira-category' );
		if ( ! is_array( $cats ) ) {
			$cats = array();
		}
		foreach ( $cats as $cat ) {
			$content .= ' ' . $cat->name; // Adds the category name.
		}
	}
	return $content;
}

You can modify the function to include the parts you want included; if you don’t need the categories, just remove that part.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.