Make WordPress Core

Opened 8 years ago

Last modified 5 years ago

#36958 new enhancement

extending has_shortcode to allow searching in custom fields

Reported by: radugroza's profile radugroza Owned by:
Milestone: Priority: normal
Severity: normal Version:
Component: Shortcodes Keywords:
Focuses: Cc:

Description

Seeing as has_shortcode is mainly used by plugin developers to search a shortcode in post_content, I'd like to open a discussion about what would be the best way to extend the has_shortcode functionality to also allow searching in custom post fields.

Problem:

  • if one uses a post_meta field to store additional content for a post ( content that may contain shortcodes and is processed when displaying the post ) - there is no way for another plugin to check if a shortcode exists in that post_meta field (without knowing the meta field, of course)
  • example: a plugin needs to enqueue a script only if the current post contains a shortcode. The way it's being handled right now is:
    if ( has_shortcode( $post->post_content, $tag ) ) {
            //enqueue script
    }
    

This of course will only work for the main post_content. If another plugin uses a post_meta field to add content to the frontend, there is no way to check if that meta field contains the shortcode.

I think one possible solution for this would be to introduce a new function, something like:

function post_has_shortcode( $tag, $post_id = null ) {
        $post = get_post( $post_id );
        if ( empty( $post ) ) {
                return false;
        }

        if ( has_shortcode( $post->post_content, $tag ) ) {
                return true;
        }

        return apply_filters( 'post_has_shortcode', false, $tag, $post_id );
}

A filter implementation for this would look like:

function custom_plugin_has_shortcode( $has_shortcode, $tag, $post_id ) {
        if ( $has_shortcode ) {
                return true;
        }
        $custom_content = get_post_meta( $post_id, 'custom_plugin_custom_content', true );

        return has_shortcode( $custom_content, $tag );
}

add_filter( 'post_has_shortcode', 'custom_plugin_has_shortcode', 10, 3 );

Another option (which is better in terms of performance) is to gather all the content before checking for shortcodes - but it's not that "clean":

function post_has_shortcode( $tag, $post_id = null ) {
        $post = get_post( $post_id );
        if ( empty( $post ) ) {
                return false;
        }

        $content_to_check = apply_filters( 'get_content_for_shortcode_check', $post->post_content, $post_id );

        return has_shortcode( $content_to_check, $tag );
}

Would there be any other approaches for this? Is this something that can go into the core?
Thanks

Change History (1)

#1 @radugroza
8 years ago

ping / bump ? :-)

Note: See TracTickets for help on using tickets.