Home » Php » php – Getting “Object of class WP_Post could not be converted to string” – when it is a string

php – Getting “Object of class WP_Post could not be converted to string” – when it is a string

Posted by: admin July 12, 2020 Leave a comment


I have the following code in my functions.php, which executes a script upon publish:

function save_new_post($post_ID) {

$site_root = '/home/forexmag/public_html/directory2';
$post = get_post($post_ID);
$title = $post->post_title;
$breaking_news = false;

$categories = get_the_category($post_ID);
if (is_array($categories) && !empty($categories))
    foreach ($categories as $cat_det)
        //this is the id for the breaking (bad) news
        if (5668 == $cat_det->cat_ID)
            $breaking_news = true;

$exec_code = "/usr/local/bin/php 
        /crons/cron_notify.php '$title' $post_ID 2 " . intval($breaking_news);
} add_action('draft_to_publish', 'save_new_post', 10, 1);

When I publish a new post I keep getting the following error:

Catchable fatal error: Object of class WP_Post could not be converted to string in /home/forexmag/public_html/wp-content/themes/forex_magnates/functions.php on line 712

This line is where I set the $exec_code var. However, as you can see, and as I confirmed via var_dump, the $title variable is a string. What am I missing?

EDIT: What’s even weirder is that when I var_dump $exec_code and kill the script, I get a perfect string:

string(121) "/usr/local/bin/php /home/forexmag/public_html/directory2/crons/cron_notify.php '2011 Free Forex Report' 9934 2 0"
How to&Answers:

Got the correct answer on WordPress Answers. Thought I should share it:

$post_ID is a WP_Post object. Your exec code should effectively be using $post_ID->ID.

function save_new_post($post_ID)


WP_Post Object ( [ID] => ...

Courtesy of vancoder

Do notice that this depends on the hook you are using. E.g if you use publish_page you get an integer (This was actually the source of my confusion)


I was getting the same error, however the solution to my problem in the end was

<?php wp_reset_query(); ?>

This was because WP_Query was being used and was interrupting the rest of the queries further down the page.

I hope this helps someone


I got that same error on my website one day but the code wasn’t the problem. The problem lies in the database. What I did was go into my database and change the siteurl and home because there was gibberish inside it. I think my website was compromise so I change the database password. This website will help you to get rid of the catchable fatal error https://www.msgdigital.com/catchable-fatal-error-object-of-class-wp_error-could-not-be-converted-to-string/ .

I tried it and trust me it worked.