首页 > 解决方案 > 查询存档页面上所有帖子的作者元数据

问题描述

当用户在我的 Wordress 网站上注册时,会自动创建一个自定义帖子(运动员),并将该用户指定为作者。自定义帖子本质上充当个人资料页面。

在他们的个人资料页面上,用户填写一堆或信息,然后total_score计算并保存为用户元数据。如果他们没有填写所有表格 - 他们将不会有一个total_score,因为它是在提交时计算的。

我为帖子(运动员)创建了一个自定义存档页面,并使用设置>阅读>帖子页面将其设置为默认帖子存档。

在发布预览模板(使用 Ele Custom Skins 和 Elementor 创建和循环)上,我添加了一个名为#total_score_circle- 的元素,如下面的屏幕截图所示。

如果该帖子的作者元中#total_score_circle没有,我想隐藏在帖子预览布局中。total_score

下面的代码目前隐藏了#total_score_circle所有帖子预览,而不仅仅是total_score作者元中不存在的那些。所以我的查询显然是关闭的。

任何帮助将不胜感激。

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 );

在此处输入图像描述

前端是使用 Elementor Pro 创建的,我使用 Elementor Custom Skin 创建了显示搜索结果的循环。

标签: phpwordpressmetadataelementorusermetadata

解决方案


感谢 Ruvee 的指导,我设法通过使用 Elementor 和下面的 PHP 在实际的自定义皮肤页面上实现一个简码来解决我的问题。

本质上,我创建了一个短代码,它使用自定义 CSS 类显示值,.total_score_circle然后使用另一个短代码来运行 if/else 语句。

如果total_score存在,则返回do_shortcode(),如果不存在,则返回一个单独的、不相关的 CSS 类。

我敢肯定这不是优雅的方式,而是与 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]' );
    }

推荐阅读