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

You can’t do this using the Relevanssi shortcode removal because that’s a binary operation: the whole shortcode is kept or removed, and there’s no way to keep only part of the shortcode.

However, you can do this with the relevanssi_post_content filter hook by removing the shortcode while keeping the attribute text. To get the same effect in excerpts, you can add the same filter function to the relevanssi_pre_excerpt_content filter hook.

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

Are you a Relevanssi Premium customer looking for support? Please use the Premium support form.

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