如何从WordPress中的分隔文件中的两个函数访问和编辑全局变量

时间:2017-01-27 09:50:04

标签: php wordpress variables global

我的短代码功能如下:
这里我使用全局变量$displayed_posts_ids,我想在另一个函数中访问和编辑它;我应该在另一个文件中重新声明它吗?

function posts_mobile($atts)
{
    global $displayed_posts_ids;
    $html = "";
    if (rw_is_mobile())
    {
        $args = array(
            'posts_per_page' => 5,
            'orderby' => 'date',
            'order' => 'DESC',
            'exclude' => array(get_the_id()),
        );
        $posts_array = get_posts($args);
        // var_dump($posts_array);
        $ids = get_the_id() . ",";
        if (count($posts_array) > 0)
        {
            $html .= "<div class='battle-block'>";
            $html .= "<div id='posts' class='row items-posts'>";
            foreach ($posts_array as $post)
            {
                $html .= show_post_selected($post->ID);
                $ids .= $post->ID . ",";
            }
            $html .= "</div></div>";
        }
        $ids = rtrim($ids, ",");
        $displayed_posts_ids .= $ids;
        $html .="<script>
                jQuery(document).ready(function(){
                    $(window).scroll(function(){
                        if ($(window).scrollTop() == $(document).height()-$(window).height()){  
                            alert('" . $displayed_posts_ids . "');
                            check_page_end();
                        }

                    });
                });
                </script>";
        return $html;
    }
}

这里是我想要编辑和访问我的全局变量的函数:

function ajax_get_other_posts()
{
    $ids_posts = explode(',', $displayed_posts_ids);
    if (isset($_REQUEST['action']) && ($_REQUEST['action'] == 'ajax_get_other_posts'))
    {
        $args = array(
            'posts_per_page' => 5,
            'orderby' => 'date',
            'order' => 'DESC',
            'exclude' => $ids_posts,
        );
        $posts_array = get_posts($args);
        if (!empty($posts_array))
        {
            $ids = "";
            foreach ($posts_array as $post)
            {
                $html .= show_post_selected($post->ID);
                $ids .= $post->ID . ",";
            }
            $displayed_posts_ids .= ',' . rtrim($ids, ",");
            $params_encoded = json_encode($html);
            echo $params_encoded;
        }

        exit;
    }
}

任何帮助将不胜感激 感谢。

1 个答案:

答案 0 :(得分:0)

如果您想要使用$displayed_posts_ids方法访问ajax_get_other_posts(),请再次拨打global变量,如下所示:

function ajax_get_other_posts(){  
    global $displayed_posts_ids;
    $ids_posts = explode(',', $displayed_posts_ids);
    //..
    //..
}

希望这有帮助!