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

Thanks!

share|improve this question

1 Answer 1

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;
  $wpdb->show_errors(true);
  $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");
  var_dump($oldest_post_id);
}

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

 
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.