[英]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 代碼片段插件。
插件鏈接: 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.