最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

shortcode - Can I pass parameters to the add_shortcode() function?

programmeradmin2浏览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

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

Share Improve this question edited Oct 7, 2020 at 19:01 Greeso asked Oct 7, 2020 at 18:50 GreesoGreeso 2,2247 gold badges33 silver badges57 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 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.

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

发布评论

评论列表(0)

  1. 暂无评论