php - 如何在短代码中获取帖子网址
问题描述
我在函数中创建了简码,以在编辑器中使用简码在页面/帖子上显示促销。
//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 字段。
解决方案
在 Post 循环中,您可以使用get_the_ID()
函数..
使用此功能,您可以在循环中获取 Post 的 ID。
并使用此 ID 在循环中获取帖子的永久链接
$post_id = get_the_ID();
get_the_permalink($post_id);
推荐阅读
- dotnetnuke-9 - DNN 自定义电子邮件 - 如何包含核心超链接
- vue.js - GraphQL Apollo 客户端 (PhpStorm) 中的格式/Prettyprint gql `template strings`
- python - 使用循环而不是手动输入创建时间列表
- python - python中for循环中的原始步骤数
- javascript - 我可以使用 parcelJS 从 javascript 库中导入所有内容吗?
- javascript - 从 JavaScript 加载外部 JavaScript 库/脚本
- php - 从值更新其他表值Codeigniter问题的表中选择
- wpf - 限制 WPF 选项卡控件中的最大选项卡项数
- python - 自定义 Dask 可遍历对象
- javascript - 应用程序脚本有关循环的奇怪行为