WP_GET_CURRENT_USER->对于空格,用户登录返回%20

时间:2019-06-09 作者:Lee Ness

我正在CF7中创建一个自定义表单,并希望通过在CF7中执行业务的快捷代码插件在表中自动创建指向用户id的链接。当用户登录只有一个单词时,它可以正常工作。但是,当用户在用户名中添加空格时,返回值会添加一个%20。不幸的是,当生成用户url时,它会将空格替换为-例如,我在Artist CPT中有一个名为Artist test(用户Id)的测试。CPT地址为https://mysite/artist/artist-test我希望下面的短代码创建的链接可以创建相同的url。但是,返回的url是//mysite/artist/artist%20test,该url不起作用。我尝试过使用urldecode,但没有用。

/*
 * Current User link shortcode
 * Use like so: [current_user_link] This is displayed only if current user is logged in.
 */

add_shortcode( \'current_user_link\', \'wppbc_current_user_link\' );
function wppbc_current_user_link( $atts, $content ) {
   if ( is_user_logged_in() ) {

      $current_user = wp_get_current_user();
      $id = $current_user->user_login;

      return "<a href=\'https://mysite/artist/{$id}\'>Custom Page Link</a>";
   }

   return ;

1 个回复
SO网友:Jacob Peattie

%20 是空间在URL/链接中的表示方式。它不存在于user_login 所有物浏览器正在添加它,因为您在href属性中添加了它。

您是如何创建此艺术家CPT的?如果你只是用艺术家的名字作为标题来创建它,那么slug不一定是用户名。它将被净化成一个有效的slug,就像帖子标题通常变成slug一样。如果您尝试使用用户登录创建链接,那么您天真地忽略了创建slug的过程,并期望它们是相同的。

如果要查找标题与用户名匹配的帖子,则应根据标题查询帖子,然后正确获取其永久链接:

function wppbc_current_user_link( $atts, $content ) {
    if ( ! is_user_logged_in() ) {
        return;
    }

    $current_user = wp_get_current_user();
    $user_login   = $current_user->user_login;

    $post = get_page_by_title( $user_login, \'OBJECT\', \'artist\' ); // Substitute \'artist\' with your CPT\'s name.

    if ( $post ) {
        $url = esc_url( get_the_permalink( $post ) );

        return "<a href=\'{$url}\'>Custom Page Link</a>";
    }
}
不过,一个更具弹性的解决方案是在创建帖子时将对帖子ID的引用保存为用户元。这样你就不必担心帖子标题不匹配。

相关推荐

如何在Functions.php中链接style.css

我是WordPress的新手;我刚开始学习WordPress。我想把风格联系起来。函数中的css。php,但我无法解决这里可能存在的问题。谁能给我指出正确的方向吗?指数php<?php get_header(); ?> <?php if ( have_posts() ) { while ( have_posts() ) { the_post();