2015-09-12 35 views
-1

我知道這對某些人來說可能看起來很奇怪,但是我想在創建時複製一篇文章。wordpress在保存/更新時創建重複文章

當創建一個職位,我想複製它追加新數據的標題,以及更新元字段和更改分類是在

這是我迄今所做的:

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。

有沒有在這附近?

回答

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

ps給你的全球一個獨特的名字!以防萬一其他東西存儲在那裏 – David

相關問題