skip to Main Content

I use

get_page_by_title() 

sometimes in my code, for example

get_page_by_title($article['title'], OBJECT, 'post');

but now documentation says i cant use it anymore. It was pretty convenient for the purpose of testing some features where I can’t use ids because of creating content on different databeses for testing purposes.
Is there any way except using WP_Query class because its look like a pain to use it just for getting link by the title of the post

I am looking for something like

get_url_by_title('title', 'post')

Any thoughts?

3

Answers


  1. Chosen as BEST ANSWER

    As mentioned @CBroe in comments, the best substitution for deprecated get_page_by_title() is get_posts() documentation. Ok, I know that documentation says: "Use WP_Query instead.", but it looks like pain.

    So back to solution. To get a single page or post by title, use

    $array_of_objects = get_posts([
        'title' => 'Post or page title',
        'post_type' => 'any',
    ]);
    $id = $array_of_objects[0];//Be sure you have an array with single post or page 
    $id = $id->ID;
    $link = get_permalink($id);
    

    There are some moments. 'post_type' => 'any' works better than particular post type. Do not forget that get_posts() returns an array of objects, so you need to refer to an array and then to object.

    But if you need to get a link for a single category, you can use

    $id = get_cat_ID($title);
    $link = get_category_link($id);
    

  2. You can try this:

    get_permalink( get_page_by_title('Monthly Events');
    

    For more detail please visit the reference.

    Login or Signup to reply.
  3. Well, since the reason to deprecate this function is stupid [corporate non-sense ala Automattic https://core.trac.wordpress.org/ticket/57041 ]

    You can just un-deprecate it! Use this function instead:

    function getPageByTitle( $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)
            ",
                $page_title
            );
        } else {
            $sql = $wpdb->prepare(
                "
                SELECT ID
                FROM $wpdb->posts
                WHERE post_title = %s
                AND post_type = %s
            ",
                $page_title,
                $post_type
            );
        }
    
        $page = $wpdb->get_var( $sql );
    
        if ( $page ) {
            return get_post( $page, $output );
        }
    
        return null;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search