0

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

2 Answers 2

2

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.

0

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

1
  • Thanks @GeorgeP, however, you are not showing how I pass the $user_defined_attributes parameter, can you show in an example please? I believe $user_defined_attributes are passed as shortcode params, and this is NOT what I want, as I explained in my question above.
    – Greeso
    Commented Oct 7, 2020 at 19:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.