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");
  • There is no variable declared $post at that moment, and even if you have access to (and using) the global $post, it's not an array. You need to run a loop to fetch the latest post first and then display the data here. Read more about the loop - codex.wordpress.org/The_Loop – Mario Peshev Nov 11 '12 at 21:29

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!

| improve this answer | |
  • Fantastic! My first program is now functional - much obliged for the help. Quick ? - why use an if statement to declare the $posts variable? Does it help prevent an error from occurring? – user1787531 Nov 11 '12 at 23:01
  • Absolutely - if get_posts() fails (for whatever reason), trying to access $posts[0] would throw an "undefined index" notice. – TheDeadMedic Nov 11 '12 at 23:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.