• I’m trying to output a shortcode on the condition that the post belongs to a specific category.

    Anyone know why this may not be working?

    <?php
    	if (in_category('travel')) {
    	    echo do_shortcode( '[cta id="3919"]' );
    	else {
    		// do nothing
    	}
    ?>
Viewing 5 replies - 1 through 5 (of 5 total)
  • Hi,

    I think you are looking similar to this.

    <?php
    if(has_category(‘travel’)){
    echo do_shortcode( ‘[cta id=”3919″]’ );
    }
    else{
    //your other stuffs here
    }
    ?>

    Thanks

    Thread Starter theplastickid

    (@theplastickid)

    Thanks for the reply, seems to have done the trick.

    Do you know is there any way to test if the category is the primary category, when using the has_category function?

    I am using this code to loop through categories and output a different shortcode depending on which category the post belongs to.

    My problem is that some posts belong to more than one top level category so I need to only take a single primary category into consideration.

    <?php
    	if(has_category('travel')){
    		echo do_shortcode( '[cta id="3919"]' );
    	}
    	elseif(has_category('freelancing')){
    		echo do_shortcode( '[cta id="3949"]' );
    	}
    	else {
    
    	}
    ?>

    Hi,

    If you want to check multiple categories then you can do it in the following way.

    <?php
    if(has_category(array(‘travel’,’freelancing’,’another category’))){
    echo do_shortcode( ‘[cta id=”3919″]’ );
    }
    else{
    //your other stuffs here
    }
    ?>

    Thanks

    Thread Starter theplastickid

    (@theplastickid)

    Thanks for your comment Clarion but this doesn’t solve the issue.

    I don’t need to check for multiple categories, I just need to check to see what is the primary category.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Echo shortcode if post is in specific category’ is closed to new replies.