复制自定义帖子类型及其帖子

时间:2012-10-02 作者:Taylor

我有一个超过100个帖子的自定义帖子类型。我想创建另一个自定义帖子类型,并使用相同的帖子标题创建相同的帖子。是否有一个简单的DB查询允许我这样做,或者我必须重新创建每个帖子?

1 个回复
SO网友:Brian Fegter

备份数据库可以很容易地做到这一点。我创建了一个概念验证供您试用。我会在运行这个之前备份数据库。

运行插件

通过设置$post_type_1$post_type_2 源和目标帖子类型的变量。

要运行此插件,您需要以管理员身份登录。然后,访问:

http://yourdomain.com/wp-admin/?duplicate-posts=magic-password

/*
Plugin Name: Post Duplicator
Description: Duplicate posts to a new post type
Version: 0.1
Author: WPSE
Author URI: http://wordpress.stackexchange.com
License: GPL2
*/

add_action(\'admin_init\', \'foo_duplicate_posts\', 99999);
function foo_duplicate_posts(){

    # Only allow admins to run the script
    if(!current_user_can(\'manage_options\'))
        return;

    # Check if keyword is set
    if(!isset($_GET[\'duplicate-posts\']))
        return;

    # Check if keyword matches
    if($_GET[\'duplicate-posts\'] !== \'magic-password\')
        return;

    global $wpdb;

    # Configure post types
    $post_type_1 = \'foo\';
    $post_type_2 = \'bar\';

    $query = $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE post_type = \'%s\'", $post_type_1);
    $posts = $wpdb->get_results($query, ARRAY_A);
    foreach($posts as $post){

        # Post info is already stored in an array
        # Set the post_type to the new post type
        $post[\'post_type\'] = $post_type_2;

        # Insert new post
        $new_post = wp_insert_post($post);

        # Proceed if new post was created
        if($new_post){
            # Print a success message to the screen
            show_message("{$post[\'post_title\']} was duplicated from #$post[\'ID\'] to #$new_post");

            # Get source post\'s post meta
            $post_meta = get_post_custom($post[\'ID\']);

            # Convert all postmeta to new post
            if(is_array($post_meta))
                foreach($post_meta as $k => $v)
                    update_post_meta($new_post, $k, $v[0]);
        }
        else
            # Print an error message to the screen
            show_message("{$post[\'post_title\']} was not duplicated.");
    }
    # Stop the admin area from loading to get a clean reading of our output messages
    exit;
}
这个插件说明了帖子的基本信息及其发布时间。它不考虑修订、自动草稿或附件。您可以在foreach循环中运行类似的循环来复制这些子帖子类型。

结束

相关推荐