I'm new to WordPress I am trying to display the first 10 posts in the database with a shortcode with this code. It's just an experiment to learn.
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');
But I get the following error on my page when the shortcode is added.
Notice: Array to string conversion in D:\Work\DGS\Cam_Rent\Site\wp-includes\shortcodes.php on line 325 Array
I checked in the database and post_content is a long text filled with HTML. Shouldn't this code make a string? My goal is to display the HTML from those posts on my page, how would I do that?
As said Mohammad Ashique Ali , it's better to not use directly wpdb, there is a lot of wordpress functions like wp_posts
:
https://codex.wordpress.org/Function_Reference/get_posts
try this:
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;
});
You can use Insert PHP Code Snippet plugin.
Plugin link: https://wordpress.org/plugins/insert-php-code-snippet/
I checked in the database and post_content is a long text filled with HTML. Shouldn't this code make a string?
No.
If you use the print_r() function to see what the value of $result
is, you'll get something like this:
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 -->
)
...
)
An array of objects .
The reason why you're getting that PHP warning is because you're trying to concatenate a string ( $content
) with an object ( $result[$i]
, which is a stdClass Object
):
$content = $content . $result[$i];
To access the actual content from your posts (and fix the problem), change that line to:
$content = $content . $result[$i]->post_html;
Notice how now we're using the post_html
property of the object to retrieve the HTML of the post.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.