get_page_by_title в Wordpress.Как использовать для получения сообщений? - PullRequest
1 голос
/ 31 июля 2010

Недавно WordPress добавил в Trac, что вы можете получать посты по заголовкам, используя:

get_page_by_title

Вместо того, чтобы обращаться к базе данных прямоЕсли бы я хотел получить сообщение под названием «моя ферма», как бы я изменил параметры, чтобы он выполнял поиск сообщения (или типа сообщения?):

$ page_title = 'Joey in the forest';

'персонаж' - это тип сообщения.Но не знаю, как с этим работать.Я предполагаю, что возвращаемым по умолчанию является идентификатор, который будет $ post-> ID.Не уверен, что будет эквивалентно, если я использую тип сообщения.

Спасибо за помощь по этому вопросу

Ответы [ 2 ]

2 голосов
/ 31 июля 2010

Я написал функцию (ссылка в отчете об ошибке), которая делает именно это:

/**
 * 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];
}
1 голос
/ 06 мая 2011

Так как я попал на эту страницу, другие тоже могут.

get_page_by_title() также обрабатывает сообщения и пользовательские типы сообщений.

Имейте в виду, что он получает первый пост / элемент страницы в базе данных, даже если пост был удален

Пример:

$post = get_page_by_title('sample-post','post');
echo $post->ID
...