繁体   English   中英

Wordpress - 如何在我的页面中显示帖子内容 html?

[英]Wordpress - How do I display post content html in my page?

我是 WordPress 的新手,我正在尝试使用带有此代码的简码显示数据库中的前 10 个帖子。 这只是一个学习的实验。

function do_hello_world()
{
    global $wpdb;
    $result = $wpdb->get_results('SELECT post_content FROM wp_posts LIMIT 10');

    $content = "";

    for ($i = 0; $i < count($result); $i++) {
        $content = $content . $result[$i];
    }

    return $content;
}
add_shortcode('hello_world', 'do_hello_world');

但是当添加简码时,我的页面上出现以下错误。

注意:数组到字符串的转换在 D:\Work\DGS\Cam_Rent\Site\wp-includes\shortcodes.php 在第 325 行数组

我检查了数据库,post_content 是一个用 HTML 填充的长文本。 这段代码不应该是一个字符串吗? 我的目标是从我页面上的这些帖子中显示 HTML,我该怎么做?

正如Mohammad Ashique Ali所说,最好不要直接使用 wpdb,有很多 wordpress 函数,如wp_posts
https://codex.wordpress.org/Function_Reference/get_posts

尝试这个:

add_shortcode("hello_world", function ($attr, $content, $tag) {


    $posts = get_posts([
        "post_type" => "post",
        "posts_per_page" => 10,
    ]);


    $result = "";

    foreach ($posts as $post) {

        $result .= $post->post_content . "<hr/>";

    }


    return $result;

});

您可以使用插入 PHP 代码片段插件。

  1. 安装插件。
  2. 然后你会得到一个侧边栏菜单,比如 XYZ PHP 代码。
  3. 添加一个新片段并编写您的代码。
  4. 将此片段插入您的页面帖子并发布。

插件链接: https://wordpress.org/plugins/insert-php-code-snippet/

我检查了数据库,post_content 是一个用 HTML 填充的长文本。 这段代码不应该是一个字符串吗?

不。

如果您使用print_r() function 来查看$result的值是什么,您将得到如下信息:

Array
(
    [0] => stdClass Object
        (
            [post_content] => <!-- wp:paragraph -->
<p>Welcome to WordPress. This is your first post. Edit or delete it, then start writing!</p>
<!-- /wp:paragraph -->
        )

    ...

)

对象数组。

您收到 PHP 警告的原因是因为您试图将字符串( $content )与 object ( $result[$i] ,这是一个stdClass Object )连接起来:

$content = $content . $result[$i];

要访问帖子中的实际内容(并解决问题),请将该行更改为:

$content = $content . $result[$i]->post_html;

请注意,现在我们如何使用 object 的post_html属性来检索帖子的 HTML。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM