Domanda

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

È stato utile?

Soluzione

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.

Altri suggerimenti

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a wordpress.stackexchange
scroll top