2016-11-28 18 views
2

我正在構建一些自定義wordpress插件,我想獲得最新的帖子,並從中獲得一些我需要的數據並返回數組。我做到了這一點,但我的問題是,我添加了這個代碼後,全局變量$ post不再是對象,現在是數組。因爲在我的debug.log中,我有很多警告「嘗試獲取非對象的屬性」,在不同的類中試圖獲取對象的屬性。例如($後-ID)

$recentPosts = wp_get_recent_posts($blogPostArguments, OBJECT); 

    $posts = array(); 
    foreach($recentPosts as $recentPost){ 
     $avatar = get_avatar_url($recentPost->post_author, 'default'); 
     $featuredImage = get_the_post_thumbnail_url($recentPost->ID); 
     $url = get_post_permalink($recentPost->ID); 
     $categories = get_the_category($recentPost->ID); 

     foreach($categories as $category){ 
      $category->url = get_category_link($category->term_id); 
     } 

     $authorFirstName = get_user_meta($recentPost->post_author, 'first_name', true); 
     $authorLastName = get_user_meta($recentPost->post_author, 'last_name', true); 
     $authorName = $authorFirstName . " " . $authorLastName; 

     $post = array(); 
     $post['title'] = $recentPost->post_title; 
     $post['content'] = $this->limitText($recentPost->post_content, 5); 
     $post['featured_image'] = $featuredImage; 
     $post['full_name'] = $authorName; 
     $post['avatar'] = $avatar; 
     $post['url'] = $url; 
     $post['categories'] = $categories; 
     array_push($posts, $post); 

}

+0

也許你會覆蓋全局$ post。使用另一個變量:'$ my_post = array();' –

回答

2

你重寫$post = array();你試圖改變變量名? like $tempPost = array();

您應該如何在您的插件中添加所有變量的前綴以避免當前或未來的數據衝突。 (通常是兩個或三個字母的縮寫)。

+1

是的我錯誤地重寫了它,沒有看到我在方法開始時添加了全局$ post變量 – tuna

0

我認爲你需要在使用它之前先對$ post進行foreach。