macak macak - 1 year ago 112
PHP Question

Wordpress global $post is changed from object to array

I'm building some custom wordpress plugin and i want to get recent posts and get some data i need from it and return array. I done this but my problem is that after i added this code global variable $post is not anymore object, it is array now. Because that in my debug.log i have lots of warnings "Trying to get property of non-object" in different class where property of object is tried to get. For example ($post-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);


Answer Source

You rewrite the $post = array(); did you try to change the variable name ? like $tempPost = array();.

Any how you should prefix all your variables in your plugin to avoid any present or future data collisions. (Usually a two or three letters acronyme).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download