1

I am trying to get some data from WordPress database tables in a plugin. For that, I am using the below code...

global $wpdb;
$findID = $wpdb->get_var("SELECT ID FROM wp_posts WHERE post_name = 'hello-world'");
echo $findID;

But it not giving me the post ID in echo? Is there anything wrong...???

2
  • I checked again and found that it was my coding problem and after fixing that, the upper one is also working. You can also use the below answer one too... – Muhammad Hassan Sep 29 '14 at 4:29
  • @ialocin Ok. Done... – Muhammad Hassan Oct 2 '14 at 4:27
6

Just to clarify the get_var() method of $wpdb does work just fine in this context:

global $wpdb;
$helloworld_id = $wpdb->get_var("SELECT ID FROM wp_posts WHERE post_name = 'hello-world'");
echo $helloworld_id;

Actually it is more practical in this context, because a single variable is returned, which is what is actually wanted.

1
  • Thanks for confirming me that I shared the right code but the problem was in my other codes so its ok now... – Muhammad Hassan Oct 2 '14 at 4:28
3

I found the solution and the correct query to fetch one data from WordPress database is below one.

global $wpdb;
$findID = $wpdb->get_results("SELECT ID FROM wp_posts WHERE post_name = 'hello-world'");
echo $findID[0]->ID;
2
  • Don't know what the problem in your setup was/is but using get_var should work just fine. There shouldn't be the need to use get_results, which in this scenario is additionally a bit impractical. – Nicolai Sep 27 '14 at 17:54
  • I checked again and found that it was my coding problem and after fixing that, the question one is also working fine. – Muhammad Hassan Oct 2 '14 at 4:29

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.