wordpress在保存/更新时创建重复的帖子

时间:2015-09-12 10:41:51

标签: php wordpress duplication

我知道这对某些人来说可能有点奇怪,但我想复制一篇关于创作的帖子。

创建帖子时,我想复制它,将新数据附加到标题,以及更新元字段和更改它所在的分类。

这是我到目前为止所做的:

add_action('wp_insert_post', 'my_add_custom_fields');
function my_add_custom_fields($post_id)
{
    if ( $_POST['post_type'] == 'products' ) {

        $my_post = array(
          'post_title'    => get_the_title(),
          'post_content'  => '',
          'post_status'   => 'publish',
          'post_type'     => 'products',
        );

        $id = wp_insert_post($my_post);
        update_post_meta($id,'keywords', get_the_title());  
        wp_set_object_terms($id, 'New Term Here', 'platform');

    }
    return true;
}

我遇到的问题是这会创建一个无限循环,创建新帖子数千次,并且不会停止,直到我重新启动apache。

周围有吗?

1 个答案:

答案 0 :(得分:0)

你需要某种控制来阻止它循环。例如设置一个全局值来计算

    $GLOBALS['control']=0;

    add_action('wp_insert_post', 'my_add_custom_fields');
    function my_add_custom_fields($post_id)
    {
        if ( $_POST['post_type'] == 'products' ) {

            //if control is on third iteration dont proceed

            if($GLOBALS['control']===2)
                return;



            //add control here!
            $GLOBALS['control']++;

            $my_post = array(
              'post_title'    => get_the_title(),
              'post_content'  => '',
              'post_status'   => 'publish',
              'post_type'     => 'products',
            );

            $id = wp_insert_post($my_post);
            update_post_meta($id,'keywords', get_the_title());  
            wp_set_object_terms($id, 'New Term Here', 'platform');

        }
        return true;
    }
相关问题