Search code examples
phphtmlwordpresswoocommercevar

How do I get the url from a php variable?


I have a php variable that fetches woocommerce product images. It works well and I have tested it. Here it is below ...

if( $product instanceof WC_Product ){
  $order_img = $product->get_image( 'full' );
} 

if I echo $order_img the variable returns the image as follows

<img width="900" height="1200" src="https://mywebsite.it/.../.../image.jpg" class="attachment-full size-full" alt="" loading="lazy">

What I am doing

What I am trying to do is to have the images taken from the variable as a background in a div. So I did this, obviously it doesn't work because instead of getting just the src link I get the img tag as shown above.

style='background-image: url("<?php echo wp_kses_post($order_img) ?>");'

So in the html I will have this

style='background-image: url("<img width="900" height="1200" src="https://mywebsite.it/.../.../image.jpg" class="attachment-full size-full" alt="" loading="lazy">");'

But I would like to achieve this

style='background-image: url("https://mywebsite.it/.../.../image.jpg");'

So my question is, how can I just retrieve the link from my variable? Is there any way to do it?


Solution

  • I have found a solution, I leave below for anyone who is in the same condition as me

    I searched a bit on google and found this post https://wordpress.stackexchange.com/questions/338390/get-url-of-products-images-woocommerce So here's how I solved it

    I added two more variables to grab the url of the image $image_id $image_url

    if( $product instanceof WC_Product ){
      $order_img = $product->get_image( 'full' );
      $image_id  = $product->get_image_id();
      $image_url = wp_get_attachment_image_url( $image_id, 'full' );
    } 
    

    After that I wrote this

    style='background-image: url("<?php echo wp_kses_post($image_url) ?>");'
    

    and I finally got this in the html

    style='background-image: url("https://mywebsite.it/.../.../image.jpg");'
    

    However I leave the question open without accepting this answer. If there are better ways of doing this, I would be happy to see how you can improve your practice. Thanks to everyone for any answers.