简体   繁体   English

仅显示已登录作者的帖子时,如何让 a 标签包装 the_title?

[英]How do I get the a tag to wrap the_title when showing only the logged-in author's post?

I am ALMOST there with this, but need help with the final piece.我几乎在那里,但在最后一块需要帮助。 I am trying to show only a link to an author's post after they log in. It works, but the snippet below displays the post title as plain text, then generates an empty <a> tag after the post title instead of wrapping the post title with the <a> .我试图在他们登录后只显示指向作者帖子的链接。它有效,但下面的代码段将帖子标题显示为纯文本,然后在帖子标题后生成一个空的<a>标签而不是包装帖子标题与<a> The link in the <a> is correct, just not wrapping the post title. <a>的链接是正确的,只是没有包装帖子标题。 What am I missing?我错过了什么?

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

The output looks like this....输出看起来像这样......

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

</div>

How do I get the <a> to wrap the post title?如何让<a>包装帖子标题?

You need to replace the_title with get_the_title .您需要将the_title替换为get_the_title the_title echoes out the title by default, hence why the title is appearing before the link. the_title默认情况下会显示标题,因此为什么标题会出现在链接之前。 get_the_title will return you the title as a value. get_the_title会将标题作为值返回。

So change the line inside the while loop to this因此,将while循环内的行更改为此

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

I'd also recommend wrapping the get_the_title function in the esc_html function ( WP Code Reference ) and the hyperlink in the esc_url function ( WP Code Reference ) to ensure you don't get any HTML/JS outputted along with the title and link.我还建议将get_the_title函数包装在esc_html函数( WP 代码参考)中,并将超链接esc_urlesc_url函数( WP 代码参考)中,以确保不会随标题和链接一起输出任何 HTML/JS。

Would end up like this:最终会是这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM