这是我到目前为止所拥有的。我绝不是一个伟大的程序员。只是个前端的家伙想让这件事开始运作。我有一个不同的博客类别的网站。例如,我有一个类别叫:食物,地点,东西。我正在尝试编写一个函数,在那里我可以执行这样的短代码:
list_post mycat=“食品”
基本上,我希望它是灵活的,所以无论我在“我的猫”里面放什么类别,它都会显示那些博客。
同样,任何帮助都将是非常感谢的。我知道我需要传递一个参数,但老实说,我不确定如何传递。这是我最大的努力。谢谢你们的支持
$args = array(
//Pass parameter here
//Something like array (
//$mycat => 'slug';
//);
);
function list_post($mycat){
$query = new WP_Query(array('category_name' => $mycat));
if($query->have_posts()):
while($query->have_posts()):the_post();
the_title();
endwhile;
else:
echo "No posts found!";
endif;
wp_reset_postdata();
}
add_shortcode('list_post', 'list_post')发布于 2015-11-23 21:04:07
您的短代码接受1参数,它是一个数组,其中包含值。因此,对于本例,$mycat看起来像这个=> array('mycat' => 'foods');,因此对于这个实例,您应该使用以下方法来提取和比较:
function list_post($atts){
$arr = shortcode_atts( array(
'mycat' => 'some_default_category',
), $atts );
//now you can call $arr['mycat']; instead of $mycat.
}发布于 2015-11-24 05:45:22
更容易使用员额()来实现这一点。
function list_post($atts){
$arr = shortcode_atts(
array(
'mycat' => 'slug',
), $atts );
$args = array('category_name' => $arr['mycat']);
$out = '';
$posts = get_posts($args);
if ($posts){
foreach ($posts as $post) {
$out .= $post->post_title . '<br />';
}
}
else {
$out .= 'No posts found!';
}
return $out;
}
add_shortcode('list_post', 'list_post');请注意,最好是从您的短代码返回输出,而不是回显它。
编辑:根据extract()建议删除@PieterGoosen's函数的使用。
https://stackoverflow.com/questions/33880565
复制相似问题