将其放置在主题功能中:
function mysite_clone_post($post_id, $post, $update) {
if(!$update && in_category(\'home cat\', $post)) { //not handled updates and will only run if in this category
$post_fields = array( \'post_author\', \'post_date\', \'post_date_gmt\', \'post_content\',
\'post_content_filtered\', \'post_title\', \'post_excerpt\', \'post_status\', \'post_type\',
\'comment_status\', \'ping_status\', \'post_password\', \'post_name\', \'to_ping\',
\'pinged\', \'post_modified\', \'post_modified_gmt\', \'post_parent\', \'menu_order\',
\'post_mime_type\', \'guid\', \'tax_input\', \'meta_input\');
$postarr = array();
foreach($post as $k => $v) if(in_array($k, $post_fields)) $postarr[$k] = $v;
$postarr[\'ID\'] = 0;
$postarr[\'post_category\'] = array(\'casa cat\');
//not handled post_parent
wp_insert_post($postarr); //not handled errors - returns false on error
}
}
add_action(\'save_post\', \'mysite_clone_post\', 10, 3);
正如代码中的注释所述,我只处理了没有帖子父级的新帖子,而忽略了错误处理。
我还假设只有两个类别,并简单地分配一个相反的类别。
更新时间:
对于自定义帖子类型和分类,请使用以下内容:
function mysite_clone_post($post_id, $post, $update) {
if(!$update && $post->post_type == \'myposttype\' && has_term(\'home cat name, id or slug\', \'mytaxonomy\', $post)) { //not handled updates and will only run if it is this custom post type and in this custom category
$post_fields = array( \'post_author\', \'post_date\', \'post_date_gmt\', \'post_content\',
\'post_content_filtered\', \'post_title\', \'post_excerpt\', \'post_status\', \'post_type\',
\'comment_status\', \'ping_status\', \'post_password\', \'post_name\', \'to_ping\',
\'pinged\', \'post_modified\', \'post_modified_gmt\', \'post_parent\', \'menu_order\',
\'post_mime_type\', \'guid\', \'tax_input\', \'meta_input\');
$postarr = array();
foreach($post as $k => $v) if(in_array($k, $post_fields)) $postarr[$k] = $v;
$postarr[\'ID\'] = 0;
//not handled post_parent
if($newid = wp_insert_post($postarr)) { //if saved successfully, add taxonomy, note that the value is assigned to $newid and not compared
wp_set_object_terms($newid, \'desired cat id or slug\', \'mytaxonomy\');
} else {
//handle errors here
}
}
}
add_action(\'save_post\', \'mysite_clone_post\', 10, 3);
此外,要处理多个类别对,可以使用一个数组,但每次添加新类别时都必须对其进行更新。我建议以这样一种方式命名(和使用)鼻涕虫,即一种鼻涕虫可以很容易地从另一种鼻涕虫派生出来。例如,“main\\u cat”和“main\\u cat\\u ar”。
那么第一行将变成:
if(!$update && $post->post_type == \'myposttype\') { //not handled updates and will only run if it is this custom post type
$terms = get_the_terms($post, \'mytaxonomy\');
if(!is_array($terms) || count(explode(\'_ar\', $terms[0]->slug)) > 1) return; // if no terms were returned or it belongs to an arabic category, exit
将术语分配给新职位的行变为
wp_set_object_terms($newid, $terms[0]->slug.\'_ar\', \'mytaxonomy\');