Home > Mobile >  How to export image links in different columns in WooCommerce?
How to export image links in different columns in WooCommerce?

Time:05-08

I want to export the image links of my products in different columns. For example like IMG1 IMG2 IMG3.

So i wrote this code below (Not Worked):

foreach( $articles as $key => $article ) {
        if ( array_key_exists( 'ID', $article ) ) {
            $i = 1;
            $product = wc_get_product( $article['ID'] );

            if ( ! empty( $product ) ) {

                $featured_img = wp_get_attachment_url( $product->get_image_id() );

                if ( ! empty( $featured_img ) ) {
                    $articles[ $key ]['Image ' . $i] = $featured_img;
                }

                $other_imgs = $product->get_gallery_image_ids();

                if ( ! empty( $other_imgs ) ) {
                    foreach ( $other_imgs as $id ) {
                        $i  ;
                        $img = wp_get_attachment_url( $id );
                        $articles[ $key ]['Image ' . $i] = $img;

UPDATE

Code returns null

CodePudding user response:

Pass the $product to the function and it will return the images of the product as an array.

function get_images( $product ) {
        $images        = $attachment_ids = array();
        $product_image = $product->get_image_id();

        // Add featured image.
        if ( ! empty( $product_image ) ) {
            $attachment_ids[] = $product_image;
        }

        // add gallery images.
        $attachment_ids = array_merge( $attachment_ids, $product->get_gallery_image_ids() );

        // Build image data.
        foreach ( $attachment_ids as $position => $attachment_id ) {

            $attachment_post = get_post( $attachment_id );

            if ( is_null( $attachment_post ) ) {
                continue;
            }

            $attachment = wp_get_attachment_image_src( $attachment_id, 'full' );

            if ( ! is_array( $attachment ) ) {
                continue;
            }

            $images[] = array(
                'id'         => (int) $attachment_id,
                'src'        => current( $attachment ),
                'title'      => get_the_title( $attachment_id ),
                'alt'        => get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ),
            );
        }

        // Set a placeholder image if the product has no images set.
        if ( empty( $images ) ) {

            $images[] = array(
                'id'         => 0,
                'src'        => wc_placeholder_img_src(),
                'title'      => __( 'Placeholder', 'woocommerce' ),
                'alt'        => __( 'Placeholder', 'woocommerce' ),
            );
        }

        return $images;
    }
  • Related