2

最近、Wordpress が Trac に追加され、以下を使用してタイトルで投稿を取得できるようになりました。

get_page_by_title

データベースを直接クエリする代わりに。「私の農場」というタイトルの投稿を取得したい場合、投稿 (または投稿タイプ?) を検索するようにパラメーターを変更するにはどうすればよいですか?

$page_title='森のジョーイ';

'character' は投稿タイプです。しかし、これを操作する方法がわかりません。デフォルトの戻り値は id であると仮定します。これは $post->ID になります。投稿タイプを使用する場合、何が同等になるかわかりません。

これに関する誰かの助けをありがとう

4

2 に答える 2

2

このページにたどり着いたので、他の人も同様かもしれません。

get_page_by_title()投稿とカスタム投稿タイプも処理します。

投稿がゴミ箱に移動された場合でも、データベース内の最初の投稿/ページ アイテムが取得されることに注意してください。

サンプル:

$post = get_page_by_title('sample-post','post');
echo $post->ID
于 2011-05-05T21:45:24.663 に答える
2

まさにそれを行う関数(バグレポートにリンクされています)を作成しました:

/**
 * 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];
}
于 2010-07-31T06:02:59.603 に答える