Can I pass parameters to the add_shortcode() function?

As the title states, I need to pass at least one parameter, maybe more, to the add_shortcode() function. In other words, those parameters I am passing will be used in the callback function of add_shortcode(). How can I do that?

Please note, those have NOTHING to do with the following structure [shortcode 1 2 3] where 1, 2, and 3 are the parameters passed by the user. In my case, the parameters are for programming purposes only and should not be the user’s responsibility.

Thanks

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can use a closure for that together with the use keyword. Simple example:

$dynamic_value = 4;

add_shortcode( 'shortcodename', 
    function( $attributes, $content, $shortcode_name ) use $dynamic_value 
    {
        return $dynamic_value;
    }
);

See also Passing a parameter to filter and action functions.

Method 2

You can pass an array of attributes ($atts) in the callback function that will run whenever you run add_shortcode().

notice the $user_defined_attributes in the following example:

add_shortcode( 'faq', 'process_the_faq_shortcode' );
/**
 * Process the FAQ Shortcode to build a list of FAQs.
 *
 * @since 1.0.0
 *
 * @param array|string $user_defined_attributes User defined attributes for this shortcode instance
 * @param string|null $content Content between the opening and closing shortcode elements
 * @param string $shortcode_name Name of the shortcode
 *
 * @return string
 */
function process_the_faq_shortcode( $user_defined_attributes, $content, $shortcode_name ) {
    $attributes = shortcode_atts(
        array(
            'number_of_faqs' => 10,
            'class'          => '',
        ),
        $user_defined_attributes,
        $shortcode_name
    );

    // do the processing

    // Call the view file, capture it into the output buffer, and then return it.
    ob_start();
    include( __DIR__ . '/views/faq-shortcode.php' );
    return ob_get_clean();
}

reference: hellofromtonya


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x