Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save theperfectwill/688967d9cc634f44b1fc49aaca7173d2 to your computer and use it in GitHub Desktop.
Save theperfectwill/688967d9cc634f44b1fc49aaca7173d2 to your computer and use it in GitHub Desktop.
WooCommerce: display more recent version of a product notice
<?php
// Display Fields
add_action( 'woocommerce_product_options_related', 'woo_add_custom_fields' );
// Save Fields
add_action( 'woocommerce_process_product_meta', 'woo_add_custom_fields_save' );
// Display notice on proeuct page
add_action( 'woocommerce_single_product_summary', 'woo_display_more_recent_product_notice', 10 );
function woo_add_custom_fields() {
global $woocommerce, $post;
echo '<div class="options_group">';
?>
<p class="form-field">
<label for="more_recent_product_ids"><?php _e( 'More recent product', 'woocommerce' ); ?></label>
<input type="hidden" class="wc-product-search" style="width: 50%;" id="more_recent_product_ids" name="more_recent_product_ids" data-placeholder="<?php esc_attr_e( 'Search for a product&hellip;', 'woocommerce' ); ?>" data-action="woocommerce_json_search_products" data-multiple="true" data-exclude="<?php echo intval( $post->ID ); ?>" data-selected="<?php
$product_ids = array_filter( array_map( 'absint', (array) get_post_meta( $post->ID, '_more_recent_product_ids', true ) ) );
$json_ids = array();
foreach ( $product_ids as $product_id ) {
$product = wc_get_product( $product_id );
if ( is_object( $product ) ) {
$json_ids[ $product_id ] = wp_kses_post( html_entity_decode( $product->get_formatted_name(), ENT_QUOTES, get_bloginfo( 'charset' ) ) );
}
}
echo esc_attr( json_encode( $json_ids ) );
?>" value="<?php echo implode( ',', array_keys( $json_ids ) ); ?>" /> <?php echo wc_help_tip( __( 'Choose a more recent version of that product.', 'woocommerce' ) ); ?>
</p>
<?php echo '</div>';
}
function woo_add_custom_fields_save( $post_id ){
$more_recent_product_ids = isset( $_POST['more_recent_product_ids'] ) ? array_filter( array_map( 'intval', explode( ',', $_POST['more_recent_product_ids'] ) ) ) : array();
update_post_meta( $post_id, '_more_recent_product_ids', $more_recent_product_ids );
}
function woo_display_more_recent_product_notice() {
global $post;
$more_recent_product_ids = get_post_meta( $post->ID, '_more_recent_product_ids', true );
if( $more_recent_product_ids != '' ) {
$notice = '<p class="woocommerce_more_recent_product woocommerce-message">' . sprintf( wp_kses( __( 'There is a <a href="%s">newer version</a> of this product.', 'woocommerce' ), array( 'a' => array( 'href' => array() ) ) ), esc_url( get_permalink( $more_recent_product_ids[ 0 ] ) ) ) . '</p>';
echo $notice;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment