Yotam
Yotam

Reputation: 57

How to set thumbnail size using wp query?

I'm using wp_query method to display all my woocommerce products, but I have applied Google's PageSpeed tool and found out that the images size are too large, and taking me longer to load.

I'm aware WordPress has duplication of images with different size that has been uploaded, but I don't know how to approach the size I want.

    $args = array(
        'post_type'      => 'product',
        'posts_per_page' => 12,
        'product_cat'    => $cat,
        'paged' => $paged
    );

    $loop = new WP_Query( $args );
    if (have_posts()):
    while ( $loop->have_posts() ) : $loop->the_post();
    global $product;
    ?>
    <div class="grid-item">
        <a href="<?php echo get_permalink(); ?>"> 
            <div style="position: relative;">
                <img src="<?php echo the_post_thumbnail_url(); ?>" alt="<?php echo get_the_title() ?>"/>
                <?php
                if(!$product->managing_stock() && !$product->is_in_stock()) {
                    echo '<div class="out">OUT OF STOCK</div>';
                }
                if($product->is_on_sale()){
                    echo '<div class="sale">SALE</div>';
                }
                ?>
            </div>
            <span class="title">
                <?php echo get_the_title(); ?>
            </span>
            <span class="price">
                <?php echo $product->get_price_html(); ?>
            </span>
        </a>
    </div>
    <?php
    endwhile;
  endif;

I want the images to be size 900x300.

How can I set images size using WP_Query arguments?

Upvotes: 0

Views: 555

Answers (1)

Saif A. Ratul
Saif A. Ratul

Reputation: 106

How to approach different sizes:

You need to insert the size's name (thumbnail, full, etc.) as a parameter inside the the_post_thumbnail_url() function. For example:

<?php the_post_thumbnail_url('thumbnail'); ?>

Note that the_post_thumbnail_url() echoes the url already, no need to echo it again. If you don't want the function to directly echo it, use get_the_post_thumbnail_url() instead. (Notice that the two functions require different sets and orders of parameters.)

How to set up a size:

The default sizes are thumbnail, medium, large, and full.

None of them have a dimension of 900 x 300.

You can either go to Settings->Media in your WP dashboard and change one of the settings, or you can add the following in your functions.php:

add_image_size('NEW_NAME', 900, 300);

Read about the parameters of add_image_size() function if you need any customization.

Upvotes: 1

Related Questions