I'm creating a wordpress theme and I created a shortcode to show an abstract of a post (the first image, title, and link) from a post (by its ID). To do this, I created a function to get the first image of the post:
function get_image($id)
{
global $post;
$post = get_post( $id );
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+?src=[\'"]([^\'"]+)[\'"].*?>/i', $post->post_content, $matches);
$first_img = $matches[1][0];
if (empty($first_img)) {
$first_img = get_template_directory_uri() . '/img/no-photo.png';
}
return $first_img;
}
I test this in my localhost (Windows with XAMPP: PHP 7.2, MariaDB 10.1.31) and works correctly. But in my server, the server shows me this message when i call the shortcode
<img src="<br />
<b>Notice</b>: Trying to get property 'post_content' of non-object in <b>path_to_theme/shortcodes.php</b> on line <b>152</b><br />
<br />
<b>Notice</b>: Undefined offset: 0 in <b>path_to_theme/shortcodes.php</b> on line <b>157</b><br />
.png" alt="">
In other part of my theme, I created a post metabox, and when I tried to get the post with global $post ($post->ID, PHP gave me a similar error:
Trying to get property ID of non-object in ...
I solved this deleting the global post and use the function get_the_id()
I think my problem is with the global $post
because I got a plugin for rich snippets, and now shows me this:
Notice: Trying to get property 'ID' of non-object in /wp-content/plugins/all-in-one-schemaorg-rich-snippets/functions.php on line 56
Thank You!
WP Version: Wordpress 5.2.1, OS: Debian 9 Stretch, Server: Nginx, PHP Version: PHP 7.3 fpm, DB: MariaDB: 10.1.26