简体   繁体   中英

Wordpress functions variable, cannot access from another file

I have a wordpress functions file in the themes directory running some code in order to apply custom fields to the Job Manager plugin.

The code runs fine, and everything works in order for example it allows you to enter the data and the data will then be displayed on the front end, however not where I want it to display.

I have tried including this functions file, into another php file where I am designing the look on the front end. However, when including the file the variables are not accessible and even though I am echoing the variable name out, nothing appears?

I have tried using a SESSION but even this doesn't work?

function display_job_salary_data() {
global $post;

$salary = get_post_meta( $post->ID, '_job_salary', true );
$salary = number_format($salary);

if ( $salary ) {
echo esc_html($salary);
}
}

Salary is the variable that I need to access in another php file

When a variable is created inside in a function, it's only accessible within the scope of that function.

If you want to use the value in any other way, the function needs to return the value.

Since your function name starts with display_ , it wouldn't be very intuitive if it returned something, so I would break it up into two different functions.

First function gets and returns the salary data:

function get_job_salary_data() {
    global $post;

    $salary = get_post_meta( $post->ID, '_job_salary', true );
    $salary = number_format($salary);

    return $salary;
}

The second function outputs the salary data: (Just like it did before)

function display_job_salary_data() {
    // Get the salary data from our previous function
    $salary = get_job_salary_data();

    if ( $salary ) {
        echo esc_html($salary);
    }
}

Now you can get the salary data where ever (as long as the file with the functions are included):

// Get the salary data
$salary = get_job_salary_data();

// ...or just output it, just like before
display_job_salary_data();

To read more about variable scopes, I recommend reading PHP's documentation about the subject here: http://php.net/manual/en/language.variables.scope.php

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