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?
2 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];
}
}
Your registered shortcode function can have two arguments. The first one contains attribute key-value pairs like your id="2". The second one contains content between the opening and closing tag of your shortcode.
If your shortcode function is my_shortcode_handler, you can get the attributes like so:
function my_shortcode_handler($attr, $content = null) {
$attr = shortcode_atts([
'id' => false, // default value
], $attr);
// ... do something with $attr['id']
}
shortcode_atts sets default values overwriting them with actual arguments. Meaning, it will contain the default if the user did not specify the id explicitly and just typed [my-shortcode].