1

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? :)

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It worked, thanks. Now I created a different function for every variable in the functions.php, but I can use the same php file for every wordpress page, which was what I wanted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.