-1

I know this might seem strange to some, but i would like to duplicate a post on creation.

When a post is created, i would like to duplicate it appending new data to the title, as well as updating meta fields and changing the taxonomy it is in.

Here is what i have done so far:

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

The issue i have is this creates an endless loop, creating the new post thousands of times and wont stop until i restart apache.

Is there away around this?

danyo
  • 5,686
  • 20
  • 59
  • 119

1 Answers1

0

You need some sort of control for this to stop it looping. e.g. set a global value to count

    $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;
    }
David
  • 5,897
  • 3
  • 24
  • 43