Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get WordPress Shortcode atts value from a page by coding

I have created a shortcode like, [my-shortcode id="2"] and added it in a page. I want to get the value of attribute "id" by coding, so that I can do something for [my-shortcode] which value is 2.

I'm trying to retrieve attributes value from a different function. The function will check if there is any shortcode on the page, and if so, what is the value of the 'id'? Is that possible?

like image 718
Md Iftekharul Avatar asked Apr 20 '26 16:04

Md Iftekharul


1 Answers

You can use the followinig code within your functions.php

Within your functions.php you can add a new shortcode called "my_shortcode". You can achieve this by using the add_shortcode( string $tag, callable $callback ) function.

//init shortcode => [my_shortcode id="1"]
add_shortcode('my_shortcode', 'shortcode_render_function');

//function to display your shortcode
function shortcode_render_function($atts, $content) {

    //set shortcode attributes
    $custom_atts = shortcode_atts( array(
        'id' => ''    
    ), $atts ); 
   
    //check if attribute is set
    if(!empty($custom_atts[id])){
        $id = $custom_atts[id];
    }
}
like image 91
Kalti Avatar answered Apr 23 '26 13:04

Kalti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!