WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Change class according to post category (6 posts)

  1. faryus
    Member
    Posted 1 year ago #

    Hello all.

    I'll try to be short and to the point.

    I have two categories on my blog. I want to use different formatting (both on index and single post page) for each of them. In order to do this, I'm trying to get the category name, then use an if statement to change the <div>'s class.

    Here's the code I'm using at the moment but it doesn't work properly.

    <?php
    $cat = get_category('name');
    if ($cat="test"){
    	$class="post-content-short";}
    else {
    	$class="post-content-long";}
    ?>
    
    <div class="<?php echo $class; ?>">
    	<?php the_content(); ?>
    </div>

    No matter what, the output is always "post-content-short".

    This is probably an easy thing to do, but I'm a complete newb at PHP and I have (almost) no idea what I'm doing.

    Hope someone can help.

    Thanks!

  2. esmi
    Forum Moderator
    Posted 1 year ago #

    If you just use <div <?php post_class(); ?>">, WordPress will automatically create a list of classes that you can use .

  3. faryus
    Member
    Posted 1 year ago #

    I'm not really following to be honest...

  4. esmi
    Forum Moderator
    Posted 1 year ago #

  5. alchymyth
    Forum Moderator
    Posted 1 year ago #

    for your idea, you would need to use get_the_category() http://codex.wordpress.org/Function_Reference/get_the_category

    example:

    <?php
    $cat = get_the_category($post->ID);
    if ($cat[0]->cat_name == "test"){
    	$class="post-content-short";}
    else {
    	$class="post-content-long";}
    ?>
    
    <div class="<?php echo $class; ?>">
    	<?php the_content(); ?>
    </div>

    that assumes that the post has only one category; otherwise the result might seem random.

  6. faryus
    Member
    Posted 1 year ago #

    Sorry for the late reply, I've been away for the weekend.

    Thank you all for the help, in the end alchymyth's solution solved my issue.

    Thanks!

Topic Closed

This topic has been closed to new replies.

About this Topic