Php 获取具有相同标题的帖子的最后ID

Php 获取具有相同标题的帖子的最后ID,php,wordpress,function,Php,Wordpress,Function,我需要获得具有相同标题的帖子的ID。 我正在使用posts\u exists函数,在functions.php中对其进行修改,因为我需要在前端执行此操作,但此函数返回最旧帖子的ID。我需要最新帖子的ID。 我试着换了这条线 $query=“从$wpdb中选择ID->posts WHERE 1=1” 用这个 $query=“从$wpdb中选择ID->posts ORDER BY$wpdb->posts.ID DESC,其中1=1” 但它不起作用 如何将此函数更改为具有最新的帖子ID functio

我需要获得具有相同标题的帖子的ID。 我正在使用
posts\u exists
函数,在functions.php中对其进行修改,因为我需要在前端执行此操作,但此函数返回最旧帖子的ID。我需要最新帖子的ID。 我试着换了这条线
$query=“从$wpdb中选择ID->posts WHERE 1=1”
用这个
$query=“从$wpdb中选择ID->posts ORDER BY$wpdb->posts.ID DESC,其中1=1”
但它不起作用

如何将此函数更改为具有最新的帖子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;
}


其中1=1
是一个无用的条件,因为它在这里没有任何用途。该条件对每一行都有效,并且无论如何都不会影响最终结果。 要获取最新帖子,您可以将查询重写为:

方式1:

SELECT ID 
FROM {$wpdb->prefix}posts
where post_title = %s and 
      post_type = %s
ORDER BY ID DESC LIMIT 1
 SELECT max(ID) as ID 
 FROM {$wpdb->prefix}posts 
 where post_title = %s and 
       post_type = %s
方式2:

SELECT ID 
FROM {$wpdb->prefix}posts
where post_title = %s and 
      post_type = %s
ORDER BY ID DESC LIMIT 1
 SELECT max(ID) as ID 
 FROM {$wpdb->prefix}posts 
 where post_title = %s and 
       post_type = %s
使用第二种方法将比第一种方法更有效,因为我们可以完全避免排序所有匹配行的开销