0

Assuming there are a few pages with same title, how to get id of the page that has the largest id (newest)? I have tried get_page_by_title, but it returns the smallest id (oldest).

  • Why don't you query the pages by title, order by published date then get the first item of result? – Thanh Le May 11 '18 at 7:56
1

By using wp_query you can have more control:

$title = "your title"
$q = new WP_Query (array(
            'posts_per_page' => 1,
            'title' => $title,
        ));

And then you can iterate through, but because we used posts per page 1 you'll get only 1 item. By default wp query displays the last first by date, you can change this with the orderby argument. Check here.

while ($q->have_posts()){
            $q->the_post();
            the_title();
        }

Edit: if you'll use this somewhere where you need your main loop after this code snippet, reset the loop with this:

wp_reset_postdata();
0
       $pages = get_pages(
array (
    'parent'  => 0, 
    'orderby' => 'id', 
    'order' => 'ASC',

)

); then from the variable $pages get the 0th element from the array

-1

I don't see any Wordpress functions for that, but you can do it in your own way based on the original function:

/*
* FUNC BASED ON Wordpress function: get_page_by_title ON post.php
*/

function custom_get_page_by_title( $page_title, $output = OBJECT,$post_type = 'page' ) 
{
    global $wpdb;

    if ( is_array( $post_type ) ) {
        $post_type = esc_sql( $post_type );
        $post_type_in_string = "'" . implode( "','", $post_type ) . "'";
        $sql = $wpdb->prepare( "
            SELECT ID
            FROM $wpdb->posts
            WHERE post_title = %s
            AND post_type IN ($post_type_in_string)
            ORDER BY ID DESC
        ", $page_title );
    } else {
        $sql = $wpdb->prepare( "
            SELECT ID
            FROM $wpdb->posts
            WHERE post_title = %s
            AND post_type = %s
            ORDER BY ID DESC
        ", $page_title, $post_type );
    }

    $page = $wpdb->get_var( $sql );

    if ( $page ) {
        return get_post( $page, $output );
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.