• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

WP Bitz

A curated collection of code snippets for WordPress

  • Home
  • About
  • Blog
  • Code Snippets
You are here: Home / Code Snippets / Extract data attributes from WooCommerce html tag

Extract data attributes from WooCommerce html tag

August 4, 2021

This post brought to you by RocketGeek, ButlerBlog, and the following:

 

/**
 * Extraction utility to get attributes from an HTML tag.
 * 
 * Example given defaults to WooCommerce "data-" attributes, but you could
 * provide a different prefix when calling the function.
 * 
 * Example:
 * 
 * $string = <a href="https://example.com/shop/?add-to-cart=2249" data-quantity="1" class="button product_type_simple add_to_cart_button ajax_add_to_cart added" data-product_id="2249" data-product_sku="" aria-label="Add Example Product to your cart" rel="nofollow">Add to Cart</a>
 * $array = extract_wc_data_atts( $string );
 * 
 * returns: array(
 *  [quantity] => 1
 *  [product_id] => 2249
 *  [product_sku] => 
 * )
 * 
 * @param  string  $string
 * @param  string  $prefix (optional, default: "data-")
 */
function extract_wc_data_atts( $string, $prefix = "data-" ) {
    $start = 0;
    $end = 0;

    while( strpos( $string, $prefix, $end ) ) {
        $start = strpos( $string, $prefix, $start )+strlen( $prefix );
        $end   = strpos( $string, '"', $start )-1;
        $end2  = strpos( $string, '"', $end+2 );
        $array[ substr( $string, $start, $end-$start ) ] = substr( $string, $end+2, $end2-$end-2 );
    }

    return $array;
}

Chad Butler

Primary Sidebar

Join for free!

Get free code snippets, WordPress best practices, and practical Content Marketing advice from seasoned WordPress expert Chad Butler (butlerblog):

Recent Posts

  • Bitnami WordPress Autoptimize cannot write to the cache directory
  • Create and delete WordPress sites in XAMPP with a batch file
  • How to fix “Error: MySQL Shutdown Unexpectedly” in XAMPP control panel
  • Fix missing Customizer in WordPress 6
  • Use Proofy.io API to validate WordPress registrations

Copyright © 2023 · Maker Pro on Genesis Framework · WordPress · Log in