GilbertOOl
GilbertOOl

Reputation: 1309

Create Boolean function to display an image in WooCommerce

I'm looking to create a function which would allow me to display an image thanks to a custom field which would be with a boolean value "true" or "false" and which would use the slug name of the product, but being only a beginner j I have some difficulty implementing it, could you help me!

Here is my current code:

function custom_title_field() {
    global $product;
    $product = get_post( $post_id );
    $slug = $product->post_name;
    // Get the field name of InputText1
    $label = get_post_meta($product, 'title', true);
    if( is_product( $post_id ) ){
        return '<h1 class="display-3"><img class="" src="'. get_template_directory_uri() .'/inc/assets/img/shop/hero/'.$slug.'_title.svg" alt="Six Stars" data-inject-svg /></h1>';
    }
}

and this code put in my single-product.php file :

<?php
  // get the post ID outside the Loop
  $post_id = get_queried_object_id();
  // print the <img>
  echo custom_title_field( $post_id );
?>

In this code, the image is displayed well but when there is no image to display, the code displays an empty wh1> <img ....> elements

I'm not sure if my explanation is clear and understandable, so I created a descriptive image for it!

enter image description here

Let me know if you have any questions.

Upvotes: 0

Views: 138

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253824

Try the following:

function custom_title_field( $post_id ) {
    if( is_product( $post_id ) && get_post_meta( $post_id, 'title', true ) ){
        $post = get_post( $post_id );
        $slug = $post->post_name;

        return '<h1 class="display-3"><img class="" src="'. get_template_directory_uri() .'/inc/assets/img/shop/hero/'.$slug.'_title.svg" alt="Six Stars" data-inject-svg /></h1>';
    }
}

For your template single-product.php:

<?php echo custom_title_field( get_the_id() ); ?>

It should solve your problem

Upvotes: 1

Related Questions