Skip to content

Instantly share code, notes, and snippets.

@mgmartel
Created December 7, 2013 16:27
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgmartel/7844792 to your computer and use it in GitHub Desktop.
Save mgmartel/7844792 to your computer and use it in GitHub Desktop.
Duplicate WP-Posts-to-Posts (https://github.com/scribu/wp-posts-to-posts/) connections when duplicating a post using Duplicate Post (http://wordpress.org/plugins/duplicate-post/) or the WooCommerce product duplicator.
<?php
add_action( 'dp_duplicate_page', 'dp_duplicate_p2p', 10, 2 );
add_action( 'dp_duplicate_post', 'dp_duplicate_p2p', 10, 2 );
// For Duplicate Product support in WooCommerce:
//add_action( 'woocommerce_duplicate_product', 'dp_duplicate_p2p', 10, 2 );
function dp_duplicate_p2p( $new_post_id, $old_post ) {
global $wpdb;
foreach( array( 'from', 'to' ) as $direction ) {
$opposite = 'from' === $direction ? 'to' : 'from';
$query = $wpdb->prepare( "SELECT * FROM $wpdb->p2p WHERE p2p_$direction = %d", $old_post->ID );
$data = $wpdb->get_results( $query );
foreach( $data as $p2p ) {
$meta = p2p_get_meta( $p2p->p2p_id );
array_walk( $meta, function( &$val ) {
$val = reset( $val );
} );
p2p_create_connection( $p2p->p2p_type, array(
$direction => $new_post_id,
$opposite => $p2p->{'p2p_' . $opposite},
'meta' => $meta
) );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment