首页 > 解决方案 > 如何在短代码中获取帖子网址

问题描述

我在函数中创建了简码,以在编辑器中使用简码在页面/帖子上显示促销。

    //Testimonial shortcode
    add_shortcode('promotions', 'adenPromotions');   
    function adenPromotions($attr, $content)
   {        
   ob_start();  
    get_template_part('./templates/promotions-loop');  
    $ret = ob_get_contents();  
    ob_end_clean();  
    return $ret;    
   }

这是我拥有的模板文件中的代码。

<?php
if ($_SESSION['selectLocation'] != '') {
$args = array( 'post_type' => 'promotion', 
          'meta_key' => 'builder',
          'posts_per_page' => 3,
          'meta_value' => $_SESSION['selectLocation']);
} else {
$args = array( 'post_type' => 'promotion',
          'posts_per_page' => 3,
          'meta_value' => 0); 
};
if ($_SESSION['selectLocation'] != ''):
?>
<div class="container-fluid px-0">
<div class="row">
    <div class="col-md-12">
        <div class="offer-section-page-ah">
            <?php
                $the_query = new WP_Query( $args );?>              
                <?php if ( $the_query->have_posts() ) : $i = 0; ?>
                    <?php while ( $the_query->have_posts() ) : 
$the_query->the_post(); $i++ ?>
                        <div class="offer-loop-page  block-<?php echo $i 
?>">
                            <div class="offer-banner-ah" 
style="background-image:url('<?php echo the_post_thumbnail_url('full') ;?>');"></div>
                            <div class="offer-right">
                                <a href="<?php echo get_permalink() ;?>"><h2 class="heading"><?php the_title() ;?></h2></a>
                                <div class="post-expirator-ah"><p><?php echo do_shortcode('[postexpirator]') ;?></p></div>
                                <div class="sub-heading"><p><?php the_excerpt() ;?></p></div>
                                <div class="more-btn-ah"><a href="<?php echo get_permalink() ;?>" class="pink">Find out more</a></div>
                            </div>
                        </div>
                    <?php endwhile; ?>
                    <?php wp_reset_postdata(); ?>        
                <?php else : ?>
                    <h2 class="heading text-center mb-0 m-0 py-4"> Sorry, no promotion available in your region.</h2>
            <?php endif; ?>
        </div>
    </div>
</div>

get_permalink() 应该在循环中返回帖子的 url,但是如果有意义的话,它会返回添加了短代码的帖子的 URL。

希望代码有意义。如果这里的代码没有意义,这里是 pastebin 版本。-> https://pastebin.com/MSNn6rKQ

编辑:显然 the_excerpt() 函数正在播放,不知道为什么,删除它并解决了问题。而是为描述创建了 ACF 字段。

标签: phpwordpress

解决方案


在 Post 循环中,您可以使用get_the_ID()函数..

使用此功能,您可以在循环中获取 Post 的 ID。

并使用此 ID 在循环中获取帖子的永久链接

$post_id = get_the_ID();
get_the_permalink($post_id);

推荐阅读