获取“WP_Post 类的对象无法转换为字符串" - 当它是字符串时 [英] Getting “Object of class WP_Post could not be converted to string” - when it is a string

查看:12
本文介绍了获取“WP_Post 类的对象无法转换为字符串" - 当它是字符串时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的functions.php中有以下代码,它在发布时执行脚本:

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;
            break;
        }
    }
}

$exec_code = "/usr/local/bin/php 
        $site_root 
        /crons/cron_notify.php '$title' $post_ID 2 " . intval($breaking_news);
exec(
    $exec_code
);
} 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

这一行是我设置 $exec_code 变量的地方.但是,正如您所看到的,正如我通过 var_dump 确认的那样,$title 变量是一个字符串.我错过了什么?

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?

更奇怪的是,当我 var_dump $exec_code 并杀死脚本时,我得到了一个完美的字符串:

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"

推荐答案

在 Wordpress Answers 上得到了正确答案.我想我应该分享它:

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

$post_ID 是一个 WP_Post 对象.您的执行代码应该有效地使用 $post_ID->ID.

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

function save_new_post($post_ID)
{
    print_r($post_ID);
    die();

退货

WP_Post Object ( [ID] => ...

vancoder

请注意,这取决于您使用的钩子.例如,如果你使用 publish_page 你会得到一个整数(这实际上是我困惑的根源)

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)

这篇关于获取“WP_Post 类的对象无法转换为字符串" - 当它是字符串时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆