Can’t get title of latest post

I’ve just started learning PHP/Wordpress yesterday – here is one of my first plugins. Unfortunately, it’s not working like it’s supposed to – the title doesn’t display. What’s wrong with my code?

function show_title_on_dashboard() {

    $newest_post_id = $post[0]->ID;

    $title = $newest_post_id->post_title;

    echo "Latest Post: $title";
}

add_action("admin_notices", "show_title_on_dashboard");

Related posts

Leave a Reply

1 comment

  1. You’re getting there! Couple of issues – you need to actually grab the latest posts before you can work on them. And post_title is not a property of the ID, but the object itself:

    if ( $posts = get_posts( 'numberposts=1' ) ) {
        $title = $posts[0]->post_title;
        // carry on sir
    }
    

    Note: Ensure you have define( 'WP_DEBUG', true ) in your wp-config.php when developing on WordPress – it will help immensely with debugging!