2017-01-27 35 views
1

這是我的短代碼函數的方式:
這裏我使用全局變量$displayed_posts_ids,我想在另一個函數中訪問和編輯;我應該在另一個文件中重新聲明它嗎?如何在WordPress中分離文件中的兩個函數訪問和編輯全局變量

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; 
    } 
} 

任何幫助將不勝感激。
謝謝。

回答

0

如果您要訪問$displayed_posts_idsajax_get_other_posts()方法比你必須再次調用global變量,就像這樣:

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

希望這有助於!

+0

仍然無法訪問它cuz當我顯示它我得到空功能ajax_get_other_posts(){ \t global $ displayed_posts_ids; \t var_dump($ displayed_posts_ids); – 1616

相關問題