Posted on

Indexing only attributes from shortcodes

I need to add some custom shortcodes to the list of the “removed” ones (so they don’t show in plain text in the results).

However, some of them are built like [shortcode_name text="Need to keep this in results"] and I would like the content in the text parameter to stay in the results.

How do I go about this?

– Duke at Remove shortcode but keep content in X parameter

This can’t be done using Relevanssi shortcode removal, because that’s a binary operation: either the whole shortcode is kept or removed. There’s no way to keep only part of the shortcode.

However, this can be done with the relevanssi_post_content filter hook by removing the shortcode while keeping the attribute text. The same filter function can be added to the relevanssi_pre_excerpt_content filter hook in order to get the same effect in excerpts.

add_filter( 'relevanssi_pre_excerpt_content', 'rlv_shortcode_attribute', 8 );
add_filter( 'relevanssi_post_content', 'rlv_shortcode_attribute', 8 );

/**
 * Indexes only the "text" attribute from the [vc_custom_heading] shortcode
 *
 * @param string $content Post content
 *
 * @return string Post content with the shortcode replaced with just the "text" attribute content.
 */
function rlv_shortcode_attribute( $content ) {
	return preg_replace( '/\[vc_custom_heading.*?text="(.*?)".*\]/im', '\1', $content );
}

Since this particular case was about a Visual Composer shortcode, it’s worth noticing the new filter must happen on priority 8 or earlier, because on priority 9, Relevanssi runs the relevanssi_remove_page_builder_shortcodes() function that removes all Visual Composer shortcodes, including this vc_custom_heading. As long as the new filter runs before the default function, there’s no problem.

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.