Reputation: 65
When a user registers on my Wordress site, a custom post (Athlete) is automatically created, with the user being assigned as the author. The custom post essentially acts as a profile page.
On their profile page, users fill out a bunch or info, and a total_score
is calculated and saved as user meta. If they do not complete all of the forms - they won't have a total_score
as it is calculated on submission.
I have created a custom archive page for the posts (athletes), and used Settings > Reading > Posts Page to set it as the default posts archive.
On the post preview template (created and looped using Ele Custom Skins and Elementor) I have added an element called #total_score_circle
- seen in the screenshot below.
I would like to hide #total_score_circle
on the post preview layout if there is no total_score
in the author meta for that post.
The below code currently hides the #total_score_circle
across all post previews, and not just the ones where total_score
doesn't exist in the author meta. So my query is clearly off.
Any help would be greatly appreciated.
function total_score_display(){
if (is_home()){
global $post;
$author_id=$post->post_author;
$total_score = get_the_author_meta('total_score', $author_id);
if(empty($total_score)) : ?>
<style type="text/css">
#total_score_circle {
display: none !important;
}
</style>
<?php endif;
}
}
add_action( 'wp_head', 'total_score_display', 10, 1 );
The frontend has been created with Elementor Pro, and I have used Elementor Custom Skin to create the loop that displays the search results.
Upvotes: 0
Views: 402
Reputation: 65
Thanks to Ruvee's guidance, I managed to solve my problem through implementing a shortcode on the actual custom skin page using Elementor and the below PHP.
Essentially I created a shortcode that displayed the value with a custom CSS class .total_score_circle
and then used another shortcode to run the if/else statement.
If total_score
exists, return do_shortcode()
, if not return a separate, irrelevant CSS class.
I'm sure it's not the elegant way to do it, but worked a treat with Elementor.
// Create shortcode to show total_score
add_shortcode('total_score_sc', 'total_score_sc');
function total_score_sc ($atts) {
$total_score = get_the_author_meta( 'total_score');
$total_score_class = '<div class="total_score_circle" >';
$total_score_class .= $total_score;
$total_score_class .= '</div>';
return $total_score_class;
}
// Create shortcode to replace above shortcode if total_score not present
add_shortcode('final_total_score_sc', 'final_total_score_sc');
function final_total_score_sc() {
global $post;
$author_id = get_post_meta( get_queried_object_id(), 'author_id' );
$total_score = get_the_author_meta( 'total_score', $author_id );
$sR = '<div class="total_score_circle_empty" >';
$sR .= '</div>';
if(empty($total_score))
return $sR;
else
return do_shortcode( '[total_score_sc]' );
}
Upvotes: 0