【问题标题】:wordpress create duplicate post on save / updatewordpress 在保存/更新时创建重复的帖子
【发布时间】:2015-12-08 20:45:24
【问题描述】:

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

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

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

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 之前不会停止。

这附近有吗?

【问题讨论】:

    标签: php wordpress duplication


    【解决方案1】:

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

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

    【讨论】:

    • ps 给你的全局一个唯一的名字!以防万一还有其他东西存放在那里
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-04
    • 1970-01-01
    • 2017-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多