我知道这对一些人来说可能看起来很奇怪,但我想复制一篇关于创作的文章。
当一个帖子被创建时,我想复制它,并向标题添加新数据,以及更新元字段和更改它所在的分类法。
到目前为止我所做的是:
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才会停止。
这附近有别的地方吗?
您需要某种控件来阻止它循环。例如,设置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;
}