Skip to content

Instantly share code, notes, and snippets.

@opicron
Last active October 20, 2022 10:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save opicron/efa778d2ccba6d66c94fdf991f5cf842 to your computer and use it in GitHub Desktop.
Save opicron/efa778d2ccba6d66c94fdf991f5cf842 to your computer and use it in GitHub Desktop.
change sku to id for woocommerce product table #php #woocommerce
<?php
function my_get_product_id_by_sku( $sku = false ) {
global $wpdb;
if( !$sku )
return null;
$product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $sku ) );
if ( $product_id )
return $product_id;
return null;
}
function my_the_content($content)
{
if ( strpos($content,"[product_table") !== false )
{
preg_match('/include=\"(.*?)\"/', $content, $match);
if ( $match )
{
$skus = explode(',', $match[1]);
$ids = array();
foreach ($skus as $key => $id)
{
$ids[$key] = my_get_product_id_by_sku($id);
}
$idlist = implode(',', $ids);
$content = preg_replace('/include=\"(.*?)\"/', 'include="'.$idlist.'"',$content);
}
}
return $content;
}
add_filter('the_content','my_the_content',10,1);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment