Sourabh
Sourabh

Reputation: 4253

php if condition not working in wordpress

For the below page: https://www.mousampictures.com/department/wedding/

I am trying to show an slider if the heading matches the provided heading:

    <div id="content" class="site-content" role="main">
        <div class="layout-full">
            <header class="entry-header">
                <h1 class="entry-title"><?php single_cat_title(); ?></h1>
           <!-- This displays 'Wedding' -->
            </header>

            <!-- wedding -->        
            <?php 
                if ( single_cat_title() == "Wedding")  {
//above line doesn't work...and instead prints wedding on the page.
                    echo do_shortcode('[metaslider id="1710"]');
                }
            ?>

            <!--portrait -->
            <?php echo do_shortcode('[metaslider id="1718"]'); ?> 

            <!--travel -->
            <?php echo do_shortcode('[metaslider id="1714"]'); ?>

        </div>

I need to show each slider, depending on the correct page.

Upvotes: 1

Views: 551

Answers (3)

Dan Nagle
Dan Nagle

Reputation: 5425

single_cat_title() takes two parameters, prefix which defaults to an empty string and display which is a boolean and defaults to true.

Change your conditional to this format:

if ("Wedding" == single_cat_title("", false)) {
    // do something
}

Upvotes: 1

josedasilva
josedasilva

Reputation: 290

The function single_cat_title, by default prints the title, if you want to retrieve the value for comparison you need to use the function ins a distinct way.

On the documentation for the function, you can see the definition:

single_cat_title( string $prefix = '', bool $display = true )

Meaning, on your case you should do the following if condition:

if ( single_cat_title('', false) == "Wedding")  {

By using the second parameter to false, you will get the desired value instead of having it printed out.

Upvotes: 1

Dan
Dan

Reputation: 9468

There are two optional parameters to include in the single_cat_title() function as per the documentation (https://developer.wordpress.org/reference/functions/single_cat_title/).

enter image description here

Try setting the second parameter ($display) to FALSE:

if ( single_cat_title('', FALSE) == "Wedding")  {
    echo do_shortcode('[metaslider id="1710"]');
}

Without setting this value you are indicating that the title should be displayed, set this to false to retrieve it instead of display it.

Upvotes: 1

Related Questions