Skip to content

Instantly share code, notes, and snippets.

@punit5658
Last active December 6, 2017 05:52
Show Gist options
  • Save punit5658/ec56a2243b5eb0f583f484482d7185ab to your computer and use it in GitHub Desktop.
Save punit5658/ec56a2243b5eb0f583f484482d7185ab to your computer and use it in GitHub Desktop.
List Magento Product Name, ID and Sku in WordPress side metabox
<?php
function wpdocs_register_meta_boxes() {
add_meta_box( 'product-list-box', __( 'Product List', 'textdomain' ), 'product_list_callback', 'articles','side' );
}
add_action( 'add_meta_boxes', 'wpdocs_register_meta_boxes' );
function product_list_callback(){ ?>
<select name="product_list[]" multiple>
<?php
global $wpdb, $post;
$post_list = get_post_meta($post->ID, 'product_list',true );
print_r( $post_list );
$results = $wpdb->get_results("SELECT
catalog_product_entity_varchar.entity_id,
catalog_product_entity_varchar.`value` AS product_name,
catalog_product_entity.sku
FROM
catalog_product_entity_varchar
INNER JOIN catalog_product_entity ON catalog_product_entity_varchar.entity_id = catalog_product_entity.entity_id
WHERE
catalog_product_entity_varchar.entity_type_id = (
SELECT
entity_type_id
FROM
eav_entity_type
WHERE
entity_type_code = 'catalog_product'
)
AND catalog_product_entity.type_id = 'configurable'
AND attribute_id = (
SELECT
attribute_id
FROM
eav_attribute
WHERE
attribute_code = 'name'
AND entity_type_id = (
SELECT
entity_type_id
FROM
eav_entity_type
WHERE
entity_type_code = 'catalog_product'
)
) ORDER BY product_name");
?><option value="">Select Multiple Product</option>
<?php foreach( $results as $product ):
$selected = in_array( $product->entity_id, $post_list ) ? 'selected="selected"' : "";
?>
}
<?php echo '<option '.$selected.' value="'.$product->entity_id.'">'.$product->product_name.'</option>'; ?>
<?php endforeach; ?>
</select>
<?php }
/**
* Save post metadata when a post is saved.
*
* @param int $post_id The post ID.
* @param post $post The post object.
* @param bool $update Whether this is an existing post being updated or not.
*/
function save_book_meta( $post_id, $post, $update ) {
/*
* In production code, $slug should be set only once in the plugin,
* preferably as a class property, rather than in each function that needs it.
*/
$post_type = get_post_type($post_id);
// If this isn't a 'book' post, don't update it.
if ( "articles" != $post_type ) return;
// - Update the post's metadata.
if ( isset( $_POST['product_list'] ) ) {
update_post_meta( $post_id, 'product_list', $_POST['product_list'] );
}
}
add_action( 'save_post', 'save_book_meta', 10, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment