Skip to content

Instantly share code, notes, and snippets.

@heymicoo
Created April 3, 2023 01:11
Show Gist options
  • Save heymicoo/ef4f48f2fec5c3d58f0a96b95192cc2f to your computer and use it in GitHub Desktop.
Save heymicoo/ef4f48f2fec5c3d58f0a96b95192cc2f to your computer and use it in GitHub Desktop.
Segregate product tabs data from the description caused by the migration of products from Shopify to WooCommerce
<?php
add_action('init', function() {
// add '?tabs_seg' to home URL to execute
if ( ! isset( $_GET['tabs_seg'] ) ) {
return;
}
// process 50 products per reload
$batch_update = 50;
$args = array(
'post_type' => 'product',
'posts_per_page' => -1
);
$products = new WP_Query( $args );
if ( $products->have_posts() ) {
$i = 0;
while ( $products->have_posts() ) {
$products->the_post();
if ( $i >= $batch_update ) {
break;
}
if ( seg_tabs( get_the_ID() ) ) {
$i++;
}
}
wp_reset_postdata();
echo 'success';
echo $i;
exit;
}
});
function seg_tabs( $product_id ) {
$product = wc_get_product( $product_id );
$desc = $product->get_description();
// seperate data by tab title wrapped with <h4> tag
$sections = explode( '<h4>', $desc, 2 );
if ( empty( $sections ) || count( $sections ) == 1 ) {
return false;
}
$final_d = $sections[0];
$tabs = $sections[1];
$tabs = '<h4>' . $tabs;
$dom = new DOMDocument();
$dom->loadHTML( '<?xml encoding="utf-8"?>' . $tabs );
$xpath = new DOMXPath( $dom );
$headings = $xpath->query('//h4');
if ( empty( $headings ) ) {
return false;
}
$result = array();
foreach ( $headings as $heading ) {
// Get the heading text
$headingText = trim ( $heading->textContent );
// Get the next sibling of the <h4> element
$sibling = $heading->nextSibling;
$contentArray = array();
// Loop through the siblings until the next <h4> element is found
while ( $sibling && $sibling->nodeName !== 'h4' ) {
if ( $sibling->nodeType == XML_ELEMENT_NODE ) {
$contentArray[] = $dom->saveHTML( $sibling );
}
$sibling = $sibling->nextSibling;
}
// Add the content to the result array with the heading text as the key
$result[ $headingText ] = implode( '', $contentArray );
}
$result['desc'] = $final_d;
// save desc data as temp backup
update_post_meta( $product_id, 'desc_backup', $desc );
// get product acf tab fields
$fields = acf_get_fields('group_622f2e70ca16d');
if ( $fields ) {
foreach ( $fields as $field ) {
$label = $field['label'];
$name = $field['name'];
// update field value per product
update_field( $name, $result[ $label ], $product_id );
}
}
// update description
$product->set_description( $result['desc'] );
$save = $product->save();
return $save;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment