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");


1 Answer 1


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.

  • 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
    Commented Jun 25, 2012 at 13:18
  • glad to know that you sorted it out Commented Jun 25, 2012 at 13:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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