Pass php dynamic variable to shortcode

I am not sure if there is a simple solution to my problem. The requirement looks simple but unable to find answer even after breaking my head for 6 hours. I have to pass variable from a php function to a shortcode and this shortcode has to pass on the this variable to another shortcode. Shortcode-1 will open a popup and the content of the popup is created by shortcode-2, content has to be changed based on the variable. How can I acheive this?

Code in my template..

 a href="#" class="open-popup-1" variable= ?php getid(); ?" ?php  echo "Click here"? /a 

popup shortcode:

[modifycontent id=$variable] 

My shortcode function

function modifycontent($atts = [], $content = null)
{
// do something to $content

 $var = atts['id']; 

 $content = gettherightcontent($var); 
 return $content;
}
add_shortcode('mc', 'modifycontent');

I tried like this, I managed to call my shortcode but unable to pass the variable.

Topic shortcode functions php Wordpress

Category Web


I see a few errors in your code...

  1. on the html, there was no quotation in front of variable

  2. on the php you say you were calling the short code [modifycontent] but by your php you should have been using [mc].

All the same, here's how I would do it:

function modifycontent ($atts, $content = null ) {
    $a = shortcode_atts( 
    array(
         'id' => '1',
        ), 
      $atts );

    return '<a href="#" class="open-popup-1" variable="'.$a['id'].'">Click here</a>';
}
add_shortcode( 'mc-shortcode', 'modifycontent' );

this would use the short code [mc-shortcode] to return:

<a href="#" class="open-popup-1" variable="1">Click here</a>

If you used this for the short code: [mc-shortcode id='1']

it would return:

<a href="#" class="open-popup-1" variable="2">Click here</a>

(Notice the variable changes)

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.