如何通过URL将当前登录用户链接到其作者页面(初学者)

时间:2022-01-03 作者:Daniel Moore

我需要一个URL,将当前登录的用户链接到其作者存档页面。我在一个类似的问题中遇到了一些代码here (见下文)。它对我有用,但不幸的是,它通过使用一个短代码链接到作者页面。

我不知道如何编辑它,使它只与一个URL,而不是短代码工作。(我是一个完全的初学者,但我努力了!)。我的最终目标是使用这个URL创建一个菜单项。

function my_users_shortcode( $atts, $content ) {
    if ( is_user_logged_in() ) {
        echo \'<a href="\' . esc_url( get_author_posts_url( wp_get_current_user()->ID ) ) .
             \'">My personal page</a>\';
    } else {
        echo \'<a href="\' . esc_url( wp_login_url() ) . \'" title="Login">Login</a>\';
    }
}
add_shortcode( \'my_shortcode\', \'my_users_shortcode\' );
在此方面的任何帮助都将不胜感激。如果可能的话,可以用外行的语言提供任何连我都能理解的答案吗!

非常感谢。

编辑:

我还发现了以下代码:

<?php 
global $current_user;
get_currentuserinfo();
echo get_author_posts_url($current_user->ID); 
?>
这可以达到目的(?)但我不知道如何将其用作HTML链接。

1 个回复
最合适的回答,由SO网友:Suman A. 整理而成

根据注释更新,以下是更新的解决方案。

Note: 复制粘贴之前,不要忘记更改somePrefix 使用any other prefix以避免与任何其他短代码冲突。

Step 1: 确保已安装此筛选器functions.php (如果没有,请复制粘贴到那里)

add_filter(\'wp_nav_menu_items\', \'do_shortcode\');
Step 2: 使用此代码段返回作者URL。将此粘贴到functions.php

add_shortcode( \'somePrefix_author_url\', function() { 
    
    $author_link = get_author_posts_url( get_current_user_id() ); // original link
    $without_protocol = trim( str_replace( array( \'http://\', \'https://\' ), \'\', $author_link ), \'/\' );
    return  $without_protocol; // returns author link without protocol
    
});
Step 3: 转到导航菜单,添加自定义菜单链接并使用[somePrefix_author_url]URL 字段和“我的个人页面”或名称字段中的其他内容。

Step 4: 从前端测试链接是否正常。

Reason for using link without protocol:

默认情况下http/ without colon 附加到shortcode 之后出于某种原因this 使现代化这可能是一个bug,也可能不是,因为这种行为可能是故意的。无论如何,上述代码可以安全使用,因为在这种情况下,WP会自动将协议附加到自定义链接。

是的,这样就可以了。对于HTML链接,而不仅仅是输出URL的函数,请从代码段中使用以下内容:

    echo \'<a href="\' . esc_url(get_author_posts_url( wp_get_current_user()->ID )) .\'">
      My personal page
    </a>\';
它应该输出超链接到当前用户作者页面的“我的个人页面”文本。

Additional Tip:您可以通过以下方式获取用户对象:

    $currentUser = wp_get_current_user();
    $currentUserID = $currentUser->ID;
    $userAuthorLink = get_author_posts_url($currentUserID);
    $userFirstName = $currentUser->first_name; 

// and so on 
而不是重复调用同一对象wp_get_current_user()global $current_user get_currentuserinfo();, 您可以调用用户对象一次,并使用其在提示中共享的属性。

看见WP_User Class 对于可用的对象属性(ID、first\\u name…)和方法(has\\u role()…)

相关推荐

Blank Blog Screen

我的博客有问题。当您在桌面上查看时,页面看起来很好。但是,如果您查看;“自定义”;page,看起来像这样:在手机上,博客看起来也是空白的。你能帮帮我吗?(博客:http://atharvnadkarni.com/blog)