skip to Main Content

I am making customization to a cliënts WordPress website. However, I need to retrieve price information from the HTML attribute to my functions.php file. The price is being calculated and added in the attribute data-field-price=”0″ as you choose more products.

<li class="pewc-group pewc-item pewc_group_3414_3415 pewc-group-products pewc-item-products pewc-field-3415 pewc-field-count-0 pewc-item-products-checkboxes pewc-active-field" data-id="pewc_group_3414_3415" data-field-id="3415" data-field-type="products" data-field-price="0" data-field-label="" data-field-value="0"></li>

Since I can’t use Javascript I need to get the value of data-field-price=”0″ ( so in this case the 0 ). How do I achieve this with only PHP? Please help.

3

Answers


  1. You can spilt it as a string using the explode method or create an hidden input on your html to catch the value like that

    <input name="data-field-price" type="hidden" value="PRICE-HERE" >
    
    Login or Signup to reply.
  2. Add an ID to the <li> in the HTML file.

    <li id="_li" class="pewc-group pewc-item pewc_group_3414_3415 pewc-group-products pewc-item-products pewc-field-3415 pewc-field-count-0 pewc-item-products-checkboxes pewc-active-field" data-id="pewc_group_3414_3415" data-field-id="3415" data-field-type="products" data-field-price="0" data-field-label="" data-field-value="0"></li>
    

    Then you can use “JavaScript” in your PHP file!
    Use file_get_contents() to read the HTML page.

    $DOM  = new DOMDocument();
    $HTML = file_get_contents("index.html");     //Read it!
    
    @$DOM->loadHTML($HTML);                      //Load it!
    $li  = $DOM->getElementById('_li');          //Get the element!
    $val = $li->getAttribute('data-field-price');//Get the price!
    
    echo $val;                                   //Write it!
    
    Login or Signup to reply.
  3. The element is produced by WooCommerce in WordPress. WordPress core, and 3rd party plugins contain a huge array of filters and actions to get information like this.

    WooCommerce’s is documented here : WooCommerce Hooks and Filters

    The filter in particular which may be of interest is : woocommerce_cart_item_price

    I am no expert of WooCommerce, but write wordpress plugins myself so I would suggest that you could get your information as follows by adding a filter into your theme (eg in your functions.php) :

    <?php
    add_filter('woocommerce_cart_item_price', 'theme_prefix_wc_cart_item_price', 10, 3); 
    function theme_prefix_wc_cart_item_price($price, $cart_item, $cart_item_key) {
      //See what $price and $cart_item can do for you
    
    }
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search