我想通过title获得帖子的id
下面的脚本显示了id的帖子内容。
$content_post = get_post($postID);
$content = $content_post->post_content;
return apply_filters('the_content', $content);
我的目标是使用标题作为参数,以便获得相关id。
你能检查一下这个代码吗?
$page = get_page_by_title(' Your page title '); // enter your page title
$pageID = $page->ID;
echo $pageID;
有关更多信息,您可以参考此链接get_page_by_title?
您可以使用get_page_by_title。您可能有多个具有相同名称的帖子,因此可能会返回多个条目。
描述
检索给定标题的帖子。如果多个帖子使用相同的标题,则会返回ID最小的帖子。
由于此函数使用MySQL的"="比较,$page_title通常会以不区分大小写的方式与默认排序进行匹配。使用
<?php
get_page_by_title( $page_title, $output, $post_type );
?>
参数
$page_title
(string) (required) Page title
Default: None
$output
(string) (optional) Output type. OBJECT, ARRAY_N, or ARRAY_A.
Default: OBJECT
$post_type
(string) (optional) Post type like 'page', 'post', 'product' etc.
Default: page
返回值
(mixed)
OBJECT, ARRAY_N, or ARRAY_A.
未找到帖子时为NULL。
查看wordpress codex。
另一种方法如下。
问题
该功能将帖子/页面名称转换为帖子/页面ID。
function get_id_by_post_name($post_name)
{
global $wpdb;
$id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name = '".$post_name."'");
return $id;
}
函数调用
调用主题中某个位置的函数。
<?php echo get_id_by_post_name('my-post-name'); ?>