如果当前用户是 post 的作者,则在前端显示图标

Show icon on frontend if current user is the author of post

当用户在我的网站上注册时,会自动创建一个 post(在自定义 post 类型下),并将用户指定为该 post 的作者。这个 post 本质上是用户的“个人资料页面”。

任何用户都可以看到任何其他用户的个人资料页面。但是,如果属于已登录用户,我希望在个人资料页面上显示一个按钮。

换句话说:如果登录用户是当前正在查看(在前端)的 post 的作者,则显示该按钮。

下面是我最接近实现我需要做的事情 - 我创建了一个带有 css ID #profile_edit_button 的按钮,并默认使用 display:none 隐藏它。下面的代码“取消隐藏”按钮,但在所有个人资料页面上。它还会抛出以下错误:

警告:未定义变量 $user_session_id 警告:未定义变量 $author_id

我使用的代码如下。任何指导将不胜感激。

 if($user_session_id == $author_id) {
    ?>
    <style type="text/css">
        #profile_edit_button {
            display: flex !important;
        }
        </style>;
    <?php } ?>

试试下面的代码。代码将进入您的活动主题 functions.php 文件。

function current_user_is_post_author(){
    if( is_single() ){
        global $post;
        if( get_current_user_id() == $post->post_author ) { ?>
            <style type="text/css">
                #profile_edit_button   {
                    display: flex !important;
                }
            </style>;
    <?php } }
}
add_action( 'wp_head', 'current_user_is_post_author', 10, 1 );