从模板代码中访问短代码参数



我是wordpress的新手,所以我遇到了这个问题。我正在使用一个快捷代码来显示基于标签的帖子。短代码看起来是这样的(我不是在引用真正的短代码,因为这里大部分都无关紧要(:

[theshortcode posts_per_page="5" taxonomy="post_tag" tax_term="265"]

我写了一个模板,可以循环浏览帖子并在页面上显示它们。在模板的底部,我想显示如下消息,这样观众就可以点击并打开页面,其中列出了所有带有ID 265标签的帖子:

See all posts

我在模板的底部使用这行代码:

<a href="<?php echo get_term_link($atts['tax_term']); ?>">See all posts</a>

但是模板没有显示任何内容。如果我对术语ID(265(进行硬编码,代码就可以工作,但显然该模板只对单个标签有用。我怎样才能做到这一点?

您的模板应该有一个变量,该变量包含术语ID值,并且可以在短代码和页脚链接中使用。

示例代码:

<?php
$termId = <set the term id for this specific page>;
do_shortcode('[theshortcode posts_per_page="5" taxonomy="post_tag" tax_term="' . $termId . '"]");
?>
<a href="<?php echo get_term_link($termId); ?>">See all posts</a>

记录:我通过遍历$wp_query对象并确定如何引用正确的成员找到了一个解决方案。以下是我的做法。谢谢你们让我走上正轨。

短代码:[theshortcode template="templates/custom-template.php" posts_per_page="5" taxonomy="post_tag" tax_term="265"]

模板:

$tax_term = $wp_query->posts->query_vars['tax_query'][0]['terms'][0]; 
$tax = $wp_query->posts->query_vars['tax_query'][0]['taxonomy'];
$the_term = get_term_by('id', (int)$tax_term, $tax);
?>
<a href="<?php echo get_term_link((int)$tax_term); ?>">See all posts in <? echo $the_term->name; ?></a>

最新更新