在Wordpress中按标题获取页面。如何使用以获取帖子?
最近,Wordpress在Trac中添加了一个功能,您可以使用以下功能按标题获取帖子: 按标题获取页面 而不是直接查询数据库。如果我想获得标题为“我的农场”的帖子,我将如何更改参数以使其搜索帖子(或帖子类型?) $page_title='Joey in the forest' “character”是一种post类型。但我不知道该怎么做。我假设默认返回的是id,它将是$post->id。不确定如果使用post类型,会有什么等效值 感谢所有人在这方面的帮助我写了(链接在bug报告中),它正是这样做的:在Wordpress中按标题获取页面。如何使用以获取帖子?,wordpress,taxonomy,Wordpress,Taxonomy,最近,Wordpress在Trac中添加了一个功能,您可以使用以下功能按标题获取帖子: 按标题获取页面 而不是直接查询数据库。如果我想获得标题为“我的农场”的帖子,我将如何更改参数以使其搜索帖子(或帖子类型?) $page_title='Joey in the forest' “character”是一种post类型。但我不知道该怎么做。我假设默认返回的是id,它将是$post->id。不确定如果使用post类型,会有什么等效值 感谢所有人在这方面的帮助我写了(链接在bug报告中),它正是这样做
/**
* 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];
}
既然我看到了这一页,其他人也可能会看到
get\u page\u by\u title()
还处理帖子和自定义帖子类型
请注意,它会获取数据库中的第一个帖子/页面项,即使帖子被丢弃
样本:
$post = get_page_by_title('sample-post','post');
echo $post->ID
事实上,刚刚发现他们添加了“post-types”参数来获取页面标题。在抄本上看到了。但是这个代码真的很好。谢谢!不知道为什么这还没有得到任何支持,这是我遇到的这个问题唯一可靠的答案,谢谢!