首页 > 解决方案 > 如何在循环中获取当前 WordPress 帖子的链接?

问题描述

下面是我的循环:

<?php if (have_posts()):
    // This function belowm is responsible for iterating through the posts
    while (have_posts()): the_post(); ?>
        <div class="col-md-4">
            <h3><?php the_title(); ?></h3>
            <?php the_content(); ?>
            <?php wp_link_pages(); ?>
            <?php get_post_permalink(); ?>
            <?php edit_post_link(); ?>
        </div>
    <?php
        endwhile; ?>
    <?php
endif; ?>

Get<?php get_post_permalink(); ?>应该显示链接,但这就是正在呈现的内容。它没有显示帖子的永久链接

在此处输入图像描述

标签: phpwordpress

解决方案


其他答案都不正确。get_the_permalink()(您也可以使用get_permalink(),因为它是别名)返回数据,而不是ECHO。因此,它永远不会打印到屏幕上(大多数带有get_前缀的 WP 功能都是这样工作的。)

你有两个选择:

  1. 使用get_permalink( get_the_ID() )传递当前的帖子 ID(如果不在循环中)并回显它。
  2. 使用the_permalink()which 将回显永久链接(在循环中);

the_permalink()

<?php if (have_posts()):
    // This function belowm is responsible for iterating through the posts
    while (have_posts()): the_post(); ?>
        <div class="col-md-4">
            <h3><?php the_title(); ?></h3>
            <?php the_content(); ?>
            <?php wp_link_pages(); ?>
            <?php the_permalink(); ?>
            <?php edit_post_link(); ?>
        </div>
    <?php
        endwhile; ?>
    <?php
endif; ?>

get_permalink()

<?php if (have_posts()):
    // This function belowm is responsible for iterating through the posts
    while (have_posts()): the_post(); ?>
        <div class="col-md-4">
            <h3><?php the_title(); ?></h3>
            <?php the_content(); ?>
            <?php wp_link_pages(); ?>
            <?php echo get_permalink(); ?>
            <?php edit_post_link(); ?>
        </div>
    <?php
        endwhile; ?>
    <?php
endif; ?>

这将回显 URL,但不会使链接可点击 - 您需要将其添加到<a>标签:

<?php if (have_posts()):
    // This function belowm is responsible for iterating through the posts
    while (have_posts()): the_post(); ?>
        <div class="col-md-4">
            <h3><?php the_title(); ?></h3>
            <?php the_content(); ?>
            <?php wp_link_pages(); ?>
            <a href="<?php the_permalink(); ?>">Click Here</a>
            <?php edit_post_link(); ?>
        </div>
    <?php
        endwhile; ?>
    <?php
endif; ?>

推荐阅读