wordpress - WordPress 中的 get_page_by_title。如何使用来获取帖子?

标签 wordpress taxonomy

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

按标题获取页面

而不是直接查询数据库。如果我想获得标题为“我的农场”的帖子,我将如何更改参数以便它搜索帖子(或帖子类型?):

$page_title='乔伊在森林里';

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

感谢任何人对此的帮助

最佳答案

我写了a function (在错误报告中链接)它正是这样做的:

/**
 * 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 - WordPress 中的 get_page_by_title。如何使用来获取帖子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3376605/

相关文章:

包含分类 slug 的 Wordpress 自定义类型永久链接

Sharepoint:如何通过 Web 服务上传包含元数据(包括分类字段)的文件

javascript - 设置主体宽度,与客户端窗口相同

php - mysql 如何合并具有相同 id 的多行

python - 使用 Wordpresslib 编辑 WordPress 帖子

mysql - WordPress:如何从自定义分类查询中排除子分类中的帖子?

css - Wordpress 主题 - 如何设置菜单样式?

php - 如何在 php 中使 Pods 管理数组值动态化?

Wordpress 使用 slug 获取分类名称