hi in a wordpress website i have to output certain thing to certain user my code is below my question is how to avoid this echoing line duplication
if (is_user_logged_in() and get_current_user_id() != get_the_author_meta('ID')) {
if (in_array('customer', (array) $user->roles)) {
if (get_current_user_id() == $authorid) { ?>
<i class="fa fa-comments send_designer_msg" designer_id="<?php echo get_the_author_meta("ID"); ?>" logo_number="<?php echo $entryno; ?>" aria-hidden="true"></i>
<?php }
} else { ?>
<i class="fa fa-comments send_designer_msg" designer_id="<?php echo get_the_author_meta("ID"); ?>" logo_number="<?php echo $entryno; ?>" aria-hidden="true"></i>
<?php }
}
any help thank you
The conditional logic is difficult to understand.
You want to display an icon (fontAwesome based) for comments – only availabe for logged in users who meet the following requirements:
Not sure, your conditional logic is set up properly as it seems to output the comment markup for any user who is not the 'designer' ... pardon me – but where's the difference between author_id and designer_id?
A slightly more DRY implementation might be this code:
<?php
$current_user_id = get_current_user_id();
$designer_id = get_the_author_meta("ID");
$author_id = '???';
$show_comment_icon = false;
if (is_user_logged_in() && $current_user_id != $designer_id ) {
// if user has role "customer"
if (in_array ('customer', (array)$user->roles)) {
// if currently logged in user is the author of the current post?
if ( $current_user_id == $author_id) {
$show_comment_icon = true;
}
} else {
// if user is not a "customer"
$show_comment_icon = true;
}
// comment icon html template
$comment_icon =
'<i
class="fa fa-comments send_designer_msg"
data-designer-id="'.$designer_id.'"
data-logo-number="'.$entry_no.'"
aria-hidden="true">
</i>';
// output your html
if($show_comment_icon){
echo $comment_icon;
}
}
?>
Even though this revised code snippet certainly flaws: Some recommendations to avoid duplicate code and improve readability in php:
enclosing/switching beween php and html code Your code is valid. However, legibility suffers. A feasable rule of thumb to decide whether to use rather enclosed php-in-html or or html-in-php is the proportion.
If there's more php processing involved (conditions, calculations, filtering etc.) better use a variable to define your html output.
If the html template part is predominant you could use something like this (similar to the default wordpress loop proposal):
<?php if($condition_fullfilled) :?>
<p>Condition is fullfilled – there is a lot more html to come!</p>
.... (200 lines of html markup)
<?php else: ?>
<p>Nothing found, matching your conditions</p>
<?php endif; ?>