简体   繁体   中英

How do you send a variable when including a php via shortcode?

I am including a PHP file on a WordPress page like this: [include filepath='/my_file.php'] The part of the functions.php that I changed to make it possible looks like this:

function include_file($atts) {
    extract(shortcode_atts(array('filepath' => NULL), $atts));
    if ($filepath!='NULL' && file_exists( trailingslashit( get_stylesheet_directory() ) . $filepath)){
    ob_start();
    include(get_stylesheet_directory() . '/' . $filepath);
    $content = ob_get_clean();
    return $content;
    }
}

However, I want to be able to send a variable with the include. It is not possible like this: [include filepath='/my_file.php?var=1'] , but maybe you get the idea.

Right now, I created a lot of different .php files which have the variables in them and included them like this: [include filepath='/my_file1.php'][include filepath='/my_file2.php'] This is really annoying to deal with and if I change something in the original php, every other one has to be changed. Is there a better way? :)

You can define a variable before an include statement and that will be visible to the file you are including.

Simple example (I want to pass $foo into my file):

inc.php:

echo "inside inc.php '" . $foo . "' << ...\n";

test.php:

function hello()
{
    $foo = 9999;
    include('inc.php');
}

hello();

which will output:

# php test.php
inside inc.php '9999' << ...

hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM