How to do Wordpress Query

0

I need to get the ID of the last post from a post_type, but I have no idea how to do this in wordpress. I've tried mysql_query() but I could not.

$consulta = mysql_fetch_array(mysql_query("SELECT * FROM wp_posts WHERE post_type='photo' ORDER BY ID DESC "));

$id = $consulta['ID']; 

But it does not retrieve the last ID

    
asked by anonymous 20.08.2014 / 05:53

2 answers

2

If you really want to make a WordPress query, you need to use $wpdb that already offers a complete interface for everything you need.

Your query could be done as follows:

global $wpdb;

$id = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_type = 'photo' ORDER BY ID DESC LIMIT 1" );

Note that in this case I used $wpdb->posts , since the installation of each one may not always have the prefix wp_ . Besides that if it were necessary to consult a different table than the standard WordPress should use something like:

{$wpdb->prefix}nome_da_tabela

Another thing I've changed in your query is that I just did it to get ID , since it does not make sense to query multiple columns if you just need one.

Just because I needed only one value, I used the $wpdb->get_var() method. This way you do not have to worry about extracting the value of an object or an array.

But generally for queries in WordPress posts you can use WP_Query or get_posts() (which creates an interface for WP_Query ).

    
20.08.2014 / 16:02
1

Use the get_posts ( link ) function, and change the post_type parameter to the name of your custom post type. To get the last post, just change the variable posts_per_page to 1.

Example:

<?php $post = get_posts(
array('posts_per_page' => 1, 'post_type' => 'meucustomposttype', 'orderby' => 'post_date', 'order' => 'DESC')
);

foreach($post as $last_post) {
    echo $last_post->ID;
}
?>

The above code returns the ID of the last post of the custom post type "meucustomposttype".

    
20.08.2014 / 14:38