0% found this document useful (0 votes)
14 views1 page

Codes To Duplicate Pages or Posts For Wordpress

This code adds a "Duplicate" link to the row actions for pages and posts in the admin. When clicked, it duplicates the page or post as a new draft, copying over the title, content, author, taxonomies, and metadata. It then redirects to edit the new duplicated draft.

Uploaded by

sharoz726
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views1 page

Codes To Duplicate Pages or Posts For Wordpress

This code adds a "Duplicate" link to the row actions for pages and posts in the admin. When clicked, it duplicates the page or post as a new draft, copying over the title, content, author, taxonomies, and metadata. It then redirects to edit the new duplicated draft.

Uploaded by

sharoz726
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

/*Add "Duplicate" link under pages/posts*/

function add_duplicate_link($actions, $post) {


if (current_user_can('edit_posts')) {
$actions['duplicate'] = '<a href="' . wp_nonce_url('admin.php?action=duplicate_post_as_draft&post=' . $post->ID) . '" title="' .
__('Duplicate this item') . '" rel="permalink">' . __('Duplicate') . '</a>';
}
return $actions;
}
add_filter('page_row_actions', 'add_duplicate_link', 10, 2);
add_filter('post_row_actions', 'add_duplicate_link', 10, 2);

/*Duplicate page/post as draft*/


function duplicate_post_as_draft() {
if (!isset($_GET['post']) || !current_user_can('edit_posts')) {
wp_die(__('You are not allowed to duplicate this item.'));
}

$post_id = absint($_GET['post']);
$post = get_post($post_id);

if (!$post || $post->post_type == 'attachment') {


wp_die(__('Invalid post type.'));
}

$new_post = array(
'post_title' => $post->post_title . ' (Duplicate)',
'post_content' => $post->post_content,
'post_status' => 'draft',
'post_author' => $post->post_author,
'post_type' => $post->post_type,
);

$new_post_id = wp_insert_post($new_post);
if ($new_post_id) {
$taxonomies = get_object_taxonomies($post->post_type);
foreach ($taxonomies as $taxonomy) {
$terms = wp_get_object_terms($post_id, $taxonomy);
foreach ($terms as $term) {
wp_set_object_terms($new_post_id, $term->slug, $taxonomy, true);
}
}

$meta_infos = get_post_meta($post_id);
foreach ($meta_infos as $meta_key => $meta_values) {
foreach ($meta_values as $meta_value) {
add_post_meta($new_post_id, $meta_key, $meta_value);
}
}

wp_redirect(admin_url('post.php?action=edit&post=' . $new_post_id));
exit;
} else {
wp_die(__('Error duplicating the item.'));
}
}
add_action('admin_action_duplicate_post_as_draft', 'duplicate_post_as_draft');

You might also like