How to Query Wordpress

Asked

Viewed 798 times

1

I need to get the ID of the last post of a post_type, but I have no idea how to do this in wordpress. I’ve tried to mysql_query() but I couldn’t.

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

$id = $consulta['ID']; 

But does not recover the last ID

2 answers

3

If you really want to make a query in Wordpress need to use the $wpdb which already offers a complete interface for everything you need.

Your consultation 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 the case used $wpdb->posts, since the installation of each can not always have the prefix wp_. In addition that if it was necessary to consult a table other than the standard Wordpress should use something like:

{$wpdb->prefix}nome_da_tabela

Another thing I changed in your consultation was that I did it just to get the ID, since it makes no sense to consult multiple columns if you only need one.

Exactly for only needing a value I used the method $wpdb->get_var(). This way you don’t have to worry about extracting the value from an object or an array.

But usually to make queries in Wordpress posts you can utilize the class WP_Query or the function get_posts() (creating an interface for the WP_Query).

1

Use the function get_posts (http://codex.wordpress.org/Template_Tags/get_posts), and change the parameter post_type for 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".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.