php - Wordpress,通过名称或 URL 获取帖子内容

标签 php wordpress custom-post-type

我在这里看到我可以使用帖子 ID 在 WordPress 中获取帖子的内容。像这样的东西:

<?php $my_postid = 83;//This is page id or post id
$content_post = get_post($my_postid);
$content = $content_post->post_content;
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]&gt;', $content);
echo $content;?>

我想要同样的东西,但是通过它的名字获取帖子。

最佳答案

你可以用

$content_post = get_posts( array( 'name' => 'yourpostname' ) ); // i.e. hello-world
if( count($content_post) )
{
    $content = $content_post[0]->post_content;
    // do whatever you want
    echo $content;
}

更新:你也可以在你的functions.php中添加这个函数,并且可以从任何地方调用它

function get_post_by_name($post_name, $post_type = 'post', $output = OBJECT) {
    global $wpdb;
    $post = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_name = %s AND post_type= %s", $post_name, $post_type ));
    if ( $post ) return get_post($post, $output);
    return null;
}

// call the function "get_post_by_name"
$content_post = get_post_by_name('hello-world');
if($content_post)
{
    $content = $content_post->post_content;
    // do whatever you want
    echo $content;
}

更新:要通过它的标题获取帖子,您可以使用

// 'Hello World!' is post title here
$content_post = get_page_by_title( 'Hello World!', OBJECT, 'post' );

或者你可以使用你的$item->item_title变量

$content_post = get_page_by_title( $item->item_title, OBJECT, 'post' );
if($content_post)
{
    $content = $content_post->post_content;
    // do whatever you want
    echo $content;
}

关于php - Wordpress,通过名称或 URL 获取帖子内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14989066/

相关文章:

php - 即使我的用户名和密码正确,仍获取 "Warning: mysqli_connect(): (2800/1045)"

php - 如何用数据库中的数据填充复选框?

javascript - 单击按钮时 jQuery 返回 PHP 脚本

wordpress - AWS Elastic Beanstalk 上传大量数据

php - 如何向 WordPress 插件添加自定义字段

php - 分页器,如何使第一页和最后一页静态并放在点之间

node.js - webpack 使用 webpack.config.js 文件失败 "module build failed: unknown word"

php - WooCommerce:如何以编程方式将多个产品添加到购物车?

php - 用于新发布的帖子的 WordPress Hook ,可以访问帖子元数据

wordpress - 当我添加自定义帖子类型永久链接重写时,我的常规帖子永久链接停止工作。无法让两者同时工作