Calling WordPress functions inside a custom class

I have created PHP object to better let me handle my custom posts. In the object I have a function that will populate the object based on the wordpress post.

public function ByPost($post) {
    $this->ID = $post->ID;
    $this->Title = $post->post_title;
    $this->Slug = $post->post_name;
    $this->Description = $post->post_content;
    $this->AlbumID = get_post_meta( $post->ID, 'albumid', true );
    return $this;
}

I then call this method from the loop.

Read More
$album = Album::Get()->ByPost($post);

The problem that I am having is that the get_post_meta function isn’t working. If I call it outside of the object it works, but within the object I don’t get anything. I don’t even get a PHP error. I am assuming there is either a namespace reference or something that I am missing, but I don’t have any idea what is causing this.

Related posts

Leave a Reply

1 comment

  1. Inside function, define $post as global and use $post->ID

    global $post;
    $this->AlbumID = get_post_meta( $post->ID, 'sandbox_description', true );
    

    You also need to change function argument name.

    change function ByPost($post){ to function ByPost($post_new){ or something else and store data in array.

    public function ByPost($post_new) {
        global $post;
        $data = array();
        $data['Title'] = $post_new->post_title;
        $data['Slug'] = $post_new->post_name;
        $data['Description'] = $post_new->post_content;
        $data['AlbumID'] = get_post_meta( $post->ID, 'sandbox_description', true );
        return $data;
    }