如何将带有参数的 WordPress 简码传递给模板 [英] How pass WordPress shortcode with Parameters to template
问题描述
我有带有子主题的模板,我编辑子模板 function.php
I have template with child theme and I edit child template function.php
目标是创建具有参数和部分模板文件的短代码
Goal is create short code witch will have parameters and part of template file
我的函数是这样的:
function my_shortcode($atts = array() ) {
extract(shortcode_atts(array(
'catid' => '5'
), $atts));
ob_start();
include(get_template_part('mynews-temp'));
return ob_get_clean();
}
add_shortcode('mynews', 'my_shortcode');
[mynews catid="5"]
短码输出必须是cat id 5的新闻查询
[mynews catid="5"]
short code output must be news query with cat id 5
这是带有查询的模板部分
this is template part with query
<?phpif ( ! defined( 'ABSPATH' ) ) {exit( 'Direct script access denied.' );}
$posts = get_posts(array(
'posts_per_page' => -1,
'post_type' => 'mynews',
'tax_query' => array(
array(
'taxonomy' => 'newstypes',
'field' => 'tag_ID',
'terms' => array('$catid')
),),));
if( $posts ): ?>
<?php foreach( $posts as $post ):
setup_postdata( $post );?>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><
<?php endforeach; ?>
<?php endif; wp_reset_postdata(); ?>
不行,找不到错误所在
附言当我使用子模板时,女巫是正确的:
P.S. witch is correct when i use child template:
include(get_template_part('mynews-temp'));
or include(locate_template('mynews-temp'));
推荐答案
您可以包含这样的模板部分:get_template_part('mynews-temp')
.无需include
,什么都不做.
You can include the template parts like this: get_template_part('mynews-temp')
. No need to include
, that does nothing.
您的其余代码运行良好.我唯一可以推荐的是简化您的代码,并获取所有常规 post
以查看问题是否出在 tax_query
中:
The rest of your code works perfectly. The only thing I could recommend is to simplify your code and just get all the regular post
s to see if the problem is in the tax_query
:
<?php
if ( ! defined( 'ABSPATH' ) ) {exit( 'Direct script access denied.' );}
$posts = get_posts(array(
'posts_per_page' => -1,
'post_type' => 'post',
));
// 'tax_query' => array(
// array(
// 'taxonomy' => 'newstypes',
// 'field' => 'tag_ID',
// 'terms' => array('$catid')
// ),),));
if( $posts ): ?>
<?php foreach( $posts as $post ):
setup_postdata( $post );?>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><
<?php endforeach; ?>
<?php endif; wp_reset_postdata(); ?>
这篇关于如何将带有参数的 WordPress 简码传递给模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!