WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm trying to get the ID of the oldest post with the post_type = job_listing and post_status = publish. I'm using the code below but it does not work. Could anyone please help me

$oldestID = mysql_query("select id from wp_posts where post_type = 'job_listing' and post_status = 'publish' order by post_date ASC");


share|improve this question
up vote 2 down vote accepted

I do not see any problem in your query (except some poor query writing styles). You did not explain 'does not work'. what you get in return? do you get any errors?

Probably you do not have any published job_listing!

However, here is how you can improve your given code:

$oldest_post_id = $wpdb->get_row("SELECT `id` FROM {$wpdb->posts} WHERE `post_type` = 'job_listing' AND `post_status` = 'publish' ORDER BY `post_date` ASC");

Please note the $wpdb->posts part. this will work safely in any wordpress installations even with custom table prefixes.

you should not use mysql_query directly. if you use this query inside a function, you need to include $wpdb in your function as below:

function myfunc(){
  global $wpdb;
  $oldest_post_id = $wpdb->get_row("SELECT `id` FROM {$wpdb->posts} WHERE `post_type` = 'job_listing' AND `post_status` = 'publish' ORDER BY `post_date` ASC");

now, you should get any query error displayed (if any) and var_dump() should give you the post ID. otherwise please get back to us what it is returning. when it is working remove 3rd and 5th line in the second example.

share|improve this answer
Hi HungryCoder, thanks for your detail explanation. I just realized that my code actually worked, i didn't know how to extract the result correctly. For example, echo $oldest_post_id gives something like Resource id #157. var_dump($oldest_post_id); gives something like object(stdClass)#259 (1) { ["id"]=> string(2) "17" } . What i need is to retrieve the number 17 into a variable. Thanks! – Pam Apple Jun 25 '12 at 13:18
glad to know that you sorted it out – HungryCoder Jun 25 '12 at 13:46

Your Answer


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.