关于特定WooCommerce产品状态更改的更改说明

时间:2019-05-18 作者:Kamran Asgari

在WooCommerce中,当我添加几行代码来更改产品描述时,在产品状态更改时,网站在提交时抛出一个错误(保存)。

我的代码:

add_action(\'transition_post_status\', \'new_product_add\', 10, 3);
function new_product_add($new_status, $old_status, $post) {
    if( 
        $old_status != \'publish\' 
        && $new_status == \'pending\' 
        && !empty($post->ID) 
        && in_array( $post->post_type, 
            array( \'product\') 
        )
    ) {
        $term = get_term_by(\'name\', \'فروش پیج اینستاگرام\', \'product_cat\');
        wp_set_object_terms($post->ID, $term->term_id, \'product_cat\', true);

        /******************************/
        $product = wc_get_product($post->ID);
        $product->set_description("something");
        $product->save();
        /******************************/
    }
}
如您所见,最后3行导致了问题页面刷新,也更新了产品描述,但给出了我和错误

“THE SITE IS EXPERIENCING TECHNICAL DIFFICULTIES”

当我移除它们时,它可以正常工作,并向我显示成功的消息

UPDATE

我用Wordpress的方式更改了这3行

wp_update_post( array(\'ID\' => $post->ID, \'post_content\' => "something"));
仍然在做这项工作,但不是成功的消息给了我这个技术错误

UPDATE II

当我打开Chrome控制台时,我也看到了这个错误

Failed to load resource: the server responded with a status of 500 () (index):1

1 个回复
最合适的回答,由SO网友:LoicTheAztec 整理而成

避免上的无限循环transition_post_status 使用时挂钩wp_update_post(), 尝试:

add_action(\'transition_post_status\', \'new_product_add\', 10, 3);
function new_product_add($new_status, $old_status, $post) {
    if( 
        $old_status != \'publish\' 
        && $new_status == \'pending\' 
        && !empty($post->ID) 
        && $post->post_type === \'product\'
    ) {
        $term = get_term_by(\'name\', \'فروش پیج اینستاگرام\', \'product_cat\');
        wp_set_object_terms($post->ID, $term->term_id, \'product_cat\', true);

        // unhook this function so it doesn\'t loop infinitely
        remove_action( \'transition_post_status\', \'new_product_add\', 10 );

        wp_update_post( array(\'ID\' => $post->ID, \'post_content\' => "something"));

        // re-hook this function
        add_action( \'transition_post_status\', \'new_product_add\', 10, 3 );
    }
}
或:

add_action(\'transition_post_status\', \'new_product_add\', 10, 3);
function new_product_add($new_status, $old_status, $post) {
    if( 
        $old_status != \'publish\' 
        && $new_status == \'pending\' 
        && !empty($post->ID) 
        && $post->post_type === \'product\'
    ) {
        $term = get_term_by(\'name\', \'فروش پیج اینستاگرام\', \'product_cat\');
        wp_set_object_terms($post->ID, $term->term_id, \'product_cat\', true);

        $product = wc_get_product($post->ID);

        // unhook this function so it doesn\'t loop infinitely
        remove_action( \'transition_post_status\', \'new_product_add\', 10 );

        $product->set_description("something");
        $product->save();

        // re-hook this function
        add_action( \'transition_post_status\', \'new_product_add\', 10, 3 );
    }
}
这可能会解决你的问题。

这是有记录的here on wp_update_post() 对于save_post