如何在 Wordpress 中按标题获取帖子?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3591295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 18:37:52  来源:igfitidea点击:

How can I get a post by title in Wordpress?

wordpress

提问by johnjohn

Wordpress 3.0

Wordpress 3.0

I want to have the contents of a specific post into a page by using the titleof the post. As far as I can tell, I can't do it directly with get_post().

我想通过使用帖子的 将特定帖子的内容放入页面title。据我所知,我不能直接用get_post().

I can assume what the brute force way might be, but I suspect there's a more elegant way?

我可以假设蛮力方式可能是什么,但我怀疑有更优雅的方式?

采纳答案by Luke

<!--1.Get post ID by post title if you know the title or the title variable-->
<?php
$posttitle = 'post_title';
$postid = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_title = '" . $posttitle . "'" );
echo $postid;
?>

<!--2.use get_post($post_id) to get whatever you want to echo-->
<?php
$getpost= get_post($postid);
$postcontent= $getpost->post_content;
echo $postcontent;
?>

回答by AlxVallejo

get_page_by_title($id, OBJECT, 'post');

There ye go.

你去吧。

回答by Erik Larsson

No need to SQL query's when you can use wordpress own functions for this.

当您可以为此使用 wordpress 自己的函数时,无需 SQL 查询。

$page = get_page_by_title( 'Startsida' );
$page_id = $page->ID;

回答by Benoit

post_exists is a good function for that :

post_exists 是一个很好的功能:

https://developer.wordpress.org/reference/functions/post_exists/

https://developer.wordpress.org/reference/functions/post_exists/

<?php

$post_id = post_exists('Your title');
// return id or 0 if post doesn't exists.

if($post_id>0)
    get_post($post_id);

回答by T.Todua

You can use this:

你可以使用这个:

1)

1)

global $wpdb;
$your_title = "yourtitle";
$id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name = $your_title");
echo $id;

or 2)

或 2)

    $slug_to_get = 'my_title_or_slug';
    // you can use custom post type too
    $posttypee='post';

    $args=array(
      'title' => $slug_to_get,
      'post_type' => $posttypee,
      'post_status' => 'publish'
      );
    $my_posts = get_posts($args);
    if( $my_posts ) {
    echo 'ID on the first post found '.$my_posts[0]->ID;
    }

回答by fuxia

See my answeron a very similar question. Do notquery the data base with an unescaped string.

请参阅对一个非常相似的问题的回答。不要使用转义的字符串查询数据库。