views:

23

answers:

1

Recently, Wordpress added in the Trac that you can fetch posts by title using:

get_page_by_title

Instead of querying the database straight up. If I wanted to get post titled "my farm", how would I change the parameters so it is searching for a post (or a post type?):

$page_title='Joey in the forest';

'character' is a post type. But don't know how to work this. I assume the default return is the id, which would be $post->ID. Not sure what would be the equivalent if I use a post type.

Thanks for anyone's help on this

A: 

I wrote a function (linked in the bug report) which does exactly that:

/**
 * Retrieves a post/page/custom-type/taxonomy ID by its title.
 *
 * Returns only the first result. If you search for a post title
 * that you have used more than once, restrict the type.
 * Or don’t use this function. :)
 * Simple usage:
 * $page_start_id = id_by_title('Start');
 *
 * To get the ID of a taxonomy (category, tag, custom) set $tax
 * to the name of this taxonomy.
 * Example:
 * $cat_css_id = id_by_title('CSS', 0, 'category');
 *
 * The result is cached internally to save db queries.
 *
 * @param  string      $title
 * @param  string      $type Restrict the post type.
 * @param  string|bool $tax Taxonomy to search for.
 * @return int         ID or -1 on failure
 */
function id_by_title($title, $type = 'any', $tax = FALSE)
{
    static $cache = array ();

    $title = mysql_real_escape_string( trim($title, '"\'') );

    // Unique index for the cache.
    $index = "$title-$type-" . ( $tax ? $tax : 0 );

    if ( isset ( $cache[$index] ) )
    {
        return $cache[$index];
    }

    if ( $tax )
    {
        $taxonomy      = get_term_by('name', $title, $tax);
        $cache[$index] = $taxonomy ? $taxonomy->term_id : -1;

        return $cache[$index];
    }

    $type_sql = 'any' == $type
        ? ''
        : "AND post_type = '"
            . mysql_real_escape_string($type) . "'";

    global $wpdb;

    $query = "SELECT ID FROM $wpdb->posts
        WHERE (
                post_status = 'publish'
            AND post_title = '$title'
            $type_sql
        )
        LIMIT 1";

    $result = $wpdb->get_results($query);
    $cache[$index] = empty ( $result ) ? -1 : (int) $result[0]->ID;

    return $cache[$index];
}
toscho
Actually, just found out they added "post types" argument to get_page_by_title. Showed it in the codex. But this code is really good. Thanks a lot!
James