title: Woocommerce set shipping method, get shipping cost
body: <p>In my functions.php file, I need to be able to set the shipping method (there's only one for this site) and then return the cost for shipping (there are a few costs set). </p>
  
  <p>I can see the <code>flat_rate</code> shipping using this:</p>
  
  <pre><code>foreach (WC()-&gt;shipping-&gt;get_shipping_methods() as $key =&gt; $value){
      echo $key;
  }
  </code></pre>
  
  <p>So it's definitely there. </p>
  
  <p>Basically, I want the shipping cost returned in from an API call. I have the API routed and all that working. It calls this function that I picked up somewhere, don't recall currently: </p>
  
  <pre><code>function pc_get_shipping(){
    $ret = array();
      foreach( WC()-&gt;session-&gt;get('shipping_for_package_0')['rates'] as $method_id =&gt; $rate ){
          if( WC()-&gt;session-&gt;get('chosen_shipping_methods')[0] == $method_id ){
              $rate_label = $rate-&gt;label; // The shipping method label name
              $rate_cost_excl_tax = floatval($rate-&gt;cost); // The cost excluding tax
              // The taxes cost
              $rate_taxes = 0;
              foreach ($rate-&gt;taxes as $rate_tax)
                  $rate_taxes += floatval($rate_tax);
              // The cost including tax
              $rate_cost_incl_tax = $rate_cost_excl_tax + $rate_taxes;
  
              $ret[] = array('label' =&gt; $rate_label, 'total' =&gt; WC()-&gt;cart-&gt;get_cart_shipping_total());
          } 
      }
    return $ret;
  }
  </code></pre>
  
  <p>But that gives me just an empty array, probably because <code>WC()-&gt;session-&gt;get('shipping_for_package_0')['rates']</code> evaluates to an empty array. </p>
  
  <p><strong>TL:DR</strong></p>
  
  <ul>
  <li><p>Guest customer shipping info is saved via <code>WC()-&gt;customer-&gt;set_shipping_address_1(wc_clean($value));</code> (etc for all values)</p></li>
  <li><p>Guest customer shipping info is correctly returned using <code>WC()-&gt;customer-&gt;get_shipping()</code>, so I believe it is being set correctly. </p></li>
  <li><p>The shipping method <code>flat_rate</code> is available via <code>WC()-&gt;shipping-&gt;get_shipping_methods()</code>.</p></li>
  <li><p>How do I <strong>set the shipping method for the current order</strong> in functions.php, in a method that will be called via REST API. </p></li>
  <li><p>How do I <strong>get the calculated shipping cost for the current order</strong> in functions.php, in a method that will be called via REST API. </p></li>
  </ul>