Checking if there is an Image inserted – if not don’t display anything

So within my Customizer I have a section that controls this Slider on the Homepage – the thing the client might not want to use all the Slider Images but all the Sliders still show anyway and the ones without an Image just show the alt tag.

Is there a way to basically check if there is a image and if not don’t display that Slide?

EDIT: I’m trying to achieve something similar to post_thumbnail as in if there is an image then displays it but if there isn’t one then don’t display it at all.

So this is how I get the Slider mage:

<div class="item active">
    <img class="img-responsive" src="https://wordpress.stackexchange.com/questions/217340/<?php echo esc_url( get_theme_mod("slider_one' ) ); ?>" alt="Slider 1">
</div>

Then I register this in my Customizer.php:

/**
 * Adding the Section for Slider
 */
$wp_customize->add_section('slideshow', array(
    'title'             => __('Slider Images', 'patti-theme'), 
    'priority'          => 60,
));

/**
 * Adding the Settings for Slider
 */
$wp_customize->add_setting('slider_one', array(
    'transport'         => 'refresh',
    'height'            => 525,
));  

/**
 * Adding the Controls for Slider
 */
$wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'slider_one_control', array(
    'label'             => __('Slider Image #1', 'patti-theme'),
    'section'           => 'slideshow',
    'settings'          => 'slider_one',    
)));

So is there a way to check if slider_one has a Image inserted and if not don’t display it.

What is shown if there is no Image inserted:

enter image description here

They then click Select Image and shows the Media Library where they can pick and Image or even Upload a new Image

How the Slider outputs the Image if there is no Image:

enter image description here

I don’t want this Slider to display at all if the src element inside the img tag is empty.

The Slider outputs the Image with this line of code:

<img class="img-responsive" src="https://wordpress.stackexchange.com/questions/217340/<?php echo esc_url( get_theme_mod("slider_one' ) ); ?>" alt="Slider 1">

2 Answers
2

Try the following code:

<div class="item active <?php
    // If image URL is empty, echo "hidden"
    echo (get_theme_mod('slider_one', '') == '' ? 'hidden' : '');
?>">
    <img class="img-responsive" src="https://wordpress.stackexchange.com/questions/217340/<?php echo esc_url( get_theme_mod("slider_one', '' ) ); ?>" alt="Slider 1">
</div>

Then use the following CSS:

.hidden { display: none }

What this will do is:

  • If no image is selected (i.e. get_theme_mod(...) == '')
  • Echo class hidden
  • The CSS will hide all elements with .hidden

Leave a Comment