WordPress 中的 get_page_by_title.如何使用获取帖子? [英] get_page_by_title in Wordpress. How to use to fetch posts?

查看:23
本文介绍了WordPress 中的 get_page_by_title.如何使用获取帖子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,Wordpress 在 Trac 中添加了您可以使用以下方法按标题获取帖子的功能:

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

get_page_by_title

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='森林中的乔伊';

$page_title='Joey in the forest';

'character' 是一种帖子类型.但不知道如何操作.我假设默认返回是 id,即 $post->ID.如果我使用帖子类型,不确定什么是等效的.

'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.

感谢任何人对此的帮助

推荐答案

我写了 一个函数(在错误报告中链接)正是这样做的:

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];
}

这篇关于WordPress 中的 get_page_by_title.如何使用获取帖子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆