wordpress: get_post() inside of a function

I have this function inside of my functions.php file in my theme:
sample code……

function getTheAuthor($x) {
global $post;
$post = get_post($x);
$author_name = get_author_name($post->post_author);
return 'author: '.$author_name;
}

end sample code
so, $x is a string (let’s say “375”)
if I change the line to $post = get_post(375); all works ok,
if I leave the line $post = get_post($x), I get a null object….
If I attempt to convert $x to an integer, it converts that string to zero. — and intval($x) = 0;
What am I missing here?

Read More

Thanks for any help

Related posts

1 comment

  1. There’s a better way to do this (and, in all cases, you shouldn’t need global $post, since you’re passing a post ID to the function). The post author is stored as a post meta field with a key of post_author. As a result, you can use the following to return the author ID of a post:

    $post_author_id = get_post_field( 'post_author', $post_id );
    

    So in your case, I’d use:

    function getTheAuthor( $post_id ) {
        $post_author_id = get_post_field( 'post_author', $post_id );
        // get_author_name() is deprecated...
        $author_name = get_the_author_meta( 'display_name', $post_author_id );
        return 'author: ' . $author_name;
    }
    

    Read more about get_the_author_meta() in the Codex.

Comments are closed.