/** * 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; }
Extract data attributes from WooCommerce html tag
This post brought to you by RocketGeek, ButlerBlog, and the following: