Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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");
share|improve this question
    
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

1 Answer 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!

share|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

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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