Load a custom URL to use as a featured image form my woocommerce products

Home » Snippets » Load a custom URL to use as a featured image form my woocommerce products
0

Created with:

Visibility: 

public

Creator: Alex

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project
					<?php

add_filter( 'woocommerce_single_product_image_thumbnail_html', 'wpturbo_replace_featured_image', 10, 2 );
add_filter( 'woocommerce_product_get_image', 'wpturbo_replace_featured_image', 10, 5 );

function wpturbo_replace_featured_image( $html, $post_id, $post_thumbnail_id = null, $size = 'woocommerce_thumbnail', $attr = array() ) {
    // Get the custom featured image URL from the post meta
    $custom_url = get_post_meta( $post_id, '_custom_featured_image_url', true );

    // If a custom URL is set, use it as the image source
    if ( ! empty( $custom_url ) ) {
        // Optionally, you can add additional attributes to the image tag
        $attr_str = '';
        foreach ( $attr as $name => $value ) {
            $attr_str .= ' ' . esc_attr( $name ) . '="' . esc_attr( $value ) . '"';
        }

        // Construct the image tag with the custom URL
        $html = sprintf( '<img src="%s" alt="%s"%s>', esc_url( $custom_url ), esc_attr( get_the_title( $post_id ) ), $attr_str );
    }

    return $html;
}
				

In this code snippet, we've added two filters:

Our wpturbo_replace_featured_image function checks for a custom URL stored in the _custom_featured_image_url post meta field. If it finds one, it constructs an <img> tag with this URL and returns it, effectively replacing the default featured image.

Replace _custom_featured_image_url with the actual meta key you've used to store the custom featured image URL. If you have additional logic or conditions for when this replacement should occur, you can include that within this function as well.

Please make sure that the custom URL stored is a valid image URL and that you handle cases where the image might not be available or the custom field is not set. This will help avoid broken images on your product pages.

Register an account to save your snippets or go Pro to get more features.