Scope: Using Variable Defined in a Function

2019-06-04 20:41发布

I have a function in a functions.php file that defines certain variables:

add_action( 'the_post', 'paginate_slide' );

function paginate_slide( $post ) {

    global $pages, $multipage, $numpages;

    if( is_single() && get_post_type() == 'post' ) {

    $multipage = 1;
    $id = get_the_ID();
    $custom = array();
    $pages = array();
    $i = 1;

    foreach( get_post_custom_keys() as $key )
        if ( false !== strpos( $key, 'slide' ) )
            $custom[$key] = get_post_meta( $id, $key, true);

    while( isset( $custom["slide{$i}-title"] ) ) {

        $page = '';
        $tzTitle = $custom["slide{$i}-title"];
        $tzImage = $custom["slide{$i}-image"];
        $tzDesc = $custom["slide{$i}-desc"];
        $tzEmbed = $custom["slide{$i}-embed"];

        $page = "<h2>{$tzTitle}</h2><img src='{$tzImage}' />";
        $pages[] = $page;
        $i++;
    }

    $numpages = count( $pages );
    }
}

I'd like to output some of these variables in a template.php file like so: <?php echo $tzDesc; ?> but I can't seem to get it to work. From what I understand about the variables scope, in order to call these variables in another place I need to define them within the global scope and call them as global in this function like I did the $pages, $multipage, $numpages;. That should allow me to plug those variables in where I need them. The problem is when I take them out of the function and define them above within the global scope the entire function stops working.

How do I need to structure this so I can call <?php echo $tzDesc; ?> anywhere in the site and have it echo the defined info?

I don't know if this matters but this is on a WordPress site.

1条回答
霸刀☆藐视天下
2楼-- · 2019-06-04 21:26

If you want to use <?php echo $tzDesc; ?> anyway, you would need to define $tzDesc as a global variable. However, I don't recommend doing so as global variables are considered poor programming practice.

A better solution would be to have the paginate_slide() add $tzDesc (and other values) to the $post object. That way you have access to these variables anytime you call the_post(). If you go this route, be sure to namespace you variables:

$post->ns_tzDesc = $tzDesc;
查看更多
登录 后发表回答