1

I wrote this code to add css class to a post title. it works in wordpress. I think it is correct code but not working

<h2><a  <?php if(get_post_meta(get_the_ID(),'hot',true) == 'on') { ?>class="hottitle" <?php } ?> title="<?php the_title_attribute(); ?>" href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>

but it dont work.

2 Answers 2

1

Write like this using ternary operator.

$key_1_value = get_post_meta(get_the_ID(),'hot',true);
// Check if the custom field has a value.
<h2><a  <?php echo (! empty( $key_1_value )) ? 'class="hottitle"' : '';  ?> title="<?php echo get_the_title_attribute(); ?>" href="<?php echo get_the_permalink() ?>"><?php echo get_the_title(); ?></a></h2>

Refer this link for more information https://developer.wordpress.org/reference/functions/get_post_meta/

Sign up to request clarification or add additional context in comments.

10 Comments

not working. look at this please: <h1 <?php if(get_post_meta(get_the_ID(),'hot',true) == 'on') { ?> class="hottitle" <?php } ?> > <a title="<?php the_title_attribute(); ?>" href="<?php the_permalink() ?>"><?php the_title(); ?></a></h1>
@kowsaralipour Please try this <h1 <?php if(get_post_meta(get_the_ID(),'hot',true) == 'on') { ?> class="hottitle" <?php } ?> > <a title="<?php echo get_the_title_attribute(); ?>" href="<?php echo get_the_permalink() ?>"><?php echo get_the_title(); ?></a></h1>
@kowsaralipour also i have updated my ans please check.
thanks. but i think this part : " 'on') ? 'class" isn't correct
@kowsaralipour please try only using this if(get_post_meta(get_the_ID(),'hot',true)). also updated in ans.
|
0
<h2><a <?php=get_post_meta(get_the_ID(),'hot',true)=='on'?'class="hottitle"':''?> title="<?php=the_title_attribute();?>" href="<?php=the_permalink()?>"><?php=the_title()?></a></h2>

3 Comments

There's no such thing as <?php=
bro I'm using it every day, please check it
It's either <?= or <?php or (if for some reason you use short tags) <?.That's it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.