Andrea A
Andrea A

Reputation: 23

Get last ID of posts with same title

I need to get the ID of the posts that have the same title. I am using the posts_exists function, modifying it in functions.php because I need this operation in the front end, but this function returns the ID of the oldest post. I need the ID of the most recent post. I tried changing this line $query = "SELECT ID FROM $wpdb->posts WHERE 1=1"; with this $query = "SELECT ID FROM $wpdb->posts ORDER BY $wpdb->posts.ID DESC WHERE 1=1"; But it doesn't work

How can I change this function to have the most recent post ID?

function post_exists_fe( $title,  $type = '' ) {
    global $wpdb;
 
    $post_title   = wp_unslash( sanitize_post_field( 'post_title', $title, 0, 'db' ) );
    $post_type    = wp_unslash( sanitize_post_field( 'post_type', $type, 0, 'db' ) );
 
    $query = "SELECT ID FROM $wpdb->posts WHERE 1=1";
    $args  = array();
  
    if ( ! empty( $title ) ) {
        $query .= ' AND post_title = %s';
        $args[] = $post_title;
        $dajenamo = end($args);
    }

    if ( ! empty( $type ) ) {
        $query .= ' AND post_type = %s';
        $args[] = $post_type;
    }
 
    if ( ! empty( $args ) ) {
     return (int) $wpdb->get_var( $wpdb->prepare( $query, $args ) );
    
    }
 
    return 0;
}

Upvotes: 1

Views: 39

Answers (1)

nice_dev
nice_dev

Reputation: 17825

where 1=1 is a useless condition as it isn't serving any purpose here. The condition will hold true for every row and doesn't affect the end result in anyway. To get the most recent post, you can rewrite query as:

Way 1:

SELECT ID 
FROM {$wpdb->prefix}posts
where post_title = %s and 
      post_type = %s
ORDER BY ID DESC LIMIT 1

Way 2:

 SELECT max(ID) as ID 
 FROM {$wpdb->prefix}posts 
 where post_title = %s and 
       post_type = %s

Using 2nd method would be much more efficient than the first method since we can completely avoid the overhead of sorting all the matched rows.

Upvotes: 1

Related Questions