创建一个字preSS短code显示类职位 [英] Create a wordpress Shortcode to display category posts
问题描述
下面是我迄今。我绝不是一个伟大的程序员。只是前端的家伙试图得到这个工作。我有不同的博客类网站。比如我有一个名为类别:食品,地点,事物。我试图写一个函数在那里我可以执行一个简短code是这样的:
[list_post mycat =食物]
块引用>基本上我希望它是灵活,不管类我把里面的mycat它会显示这些博客。
再次任何帮助将是非常美联社preciated。我知道我需要传递一个参数,但我诚实不确定如何。这是我最大的努力。感谢您的任何hekp
的$ args =阵列(
这里//传递参数
//喜欢的东西阵列(
// $ mycat => '塞';
//); );功能list_post($ mycat){
$查询=新WP_Query(阵列('CATEGORY_NAME'=> $ mycat));
如果($查询 - > have_posts()):
而(查询 - $> have_posts()):the_post();
标题();
ENDWHILE;
其他:
回声没有发现帖子!;
万一;
wp_reset_postdata();
}add_short code('list_post','list_post')
解决方案它更容易使用的 get_posts()实现这一目标。
函数list_post($的ATT){
$ ARR =短code_atts(
阵列(
mycat'=> '塞',
),$的ATT); 的$ args =阵列('CATEGORY_NAME'=> $改编['mycat']);
从$ ='';
$帖= get_posts($参数);
如果($个){
的foreach($岗位为$ POST){
从$ = $后方式> POST_TITLE。 '< BR />';
}
}
其他{
$ OUT ='没有发现帖子!';
}
返回$出;}add_short code('list_post','list_post');请注意,这是更好地从你的短code返回输出,而不是呼应了。
编辑:删除
的使用提取物()
函数按 @ PieterGoosen 的建议。Here is what I have so far. I'm in no way a great programmer. Just a front end guy trying to get this to work. I have a website with different blog categories. For example I have a category called: foods, places, things. I'm trying to write a function where I can execute a shortcode like this:
[list_post mycat="foods"]
Basically I want it to be flexible so whatever category I put inside of "mycat" it will display those blogs.
Again any help would be really appreciated. I know I need to pass a parameter, but I'm honestly unsure how. This is my best effort. Thanks for any hekp
$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')
解决方案Its easier to use get_posts() to achieve this.
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');
Note that it is better to return the output from your shortcode and not echo it.
Edit: Removed usage of
extract()
function as per @PieterGoosen's advice.这篇关于创建一个字preSS短code显示类职位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!