首页 > 解决方案 > 仅显示登录作者的帖子时,如何获取 a 标签来包装 the_title?

问题描述

我几乎在那里,但在最后一块需要帮助。我试图在他们登录后仅显示作者帖子的链接。它可以工作,但下面的代码片段将帖子标题显示为纯文本,然后在<a>帖子标题之后生成一个空标签,而不是用<a>. 中的链接<a>是正确的,只是没有包装帖子标题。我错过了什么?

<?php
                    
    $user_id = get_current_user_id();

    $args=array(
    'post_type' => 'team_fundraiser',
    'post_status' => 'published',
    'posts_per_page' => 1,
    'author' => $user_id
    );                       

    $wp_query = new WP_Query($args);
    while ( have_posts() ) : the_post();
        $team_link .= '<a href="' .get_permalink(). '">'.the_title().'</a>';
    endwhile;

    echo $team_link;
                
?>

输出看起来像这样......

<div>
    
    "My Awesome Post"
    <a href="http://localhost/mysite/my-awesome-post/"></a>

</div>

我如何获得<a>包装帖子标题?

标签: phpwordpress

解决方案


您需要替换the_titleget_the_title. the_title默认回显标题,因此标题出现在链接之前。get_the_title会将标题作为值返回给您。

所以将while循环内的行改为这个

$team_link .= '<a href="' . get_permalink(). '">'. get_the_title() . '</a>';

我还建议将函数包装在get_the_title函数中esc_htmlWP Code Reference)和esc_url函数中的超链接(WP Code Reference),以确保您不会得到任何与标题和链接一起输出的 HTML/JS。

最终会是这样:

$team_link .= '<a href="' . esc_url( get_permalink() ). '">'. esc_html( get_the_title() ) . '</a>';

推荐阅读