列出特定类别的帖子标题的短代码

我在http://codex.wordpress.org/Template_Tags/get_posts上找到了这段很棒的代码片段, 并对其进行了一些编辑以适合我。有用。

< p> < ?php$args = array( 'posts_per_page' => 0, 'offset'=> 0, 'category' => 1 ); $myposts = get_posts( $args ); foreach ( $myposts as $post ) : setup_postdata( $post ); ?> < ?php the_title(); ?> < /br> < ?php endforeach; wp_reset_postdata(); ?> < /p>

我想将其转换为带有一个可变变量的短代码-类别ID。但是, 好吧, 由于我不了解php, 所以我想到的只是:
function tytuly_postow($atts) { extract(shortcode_atts(array( 'id' => 1, ), $atts)); $args = array( 'posts_per_page' => 0, 'offset'=> 0, 'category' => $id ); $q ="< p> < ?php$myposts = get_posts( $args ); foreach ( $myposts as $post ) : setup_postdata( $post ); ?> < ?php the_title(); ?> < /br> < ?php endforeach; wp_reset_postdata(); ?> < /p> "; } add_shortcode('tytuly', 'lista_postow');

当然, 这是行不通的。我使用Karma主题并将其添加到shortcodes.php文件中。请帮忙 :)
#1你拥有的代码肯定是正确的。这是我的处理方式:
function tytuly_postow( $atts ) { extract( shortcode_atts( array( 'id' => 1, ), $atts ) ); $posts = get_posts( array( 'posts_per_page' => -1, 'post_status'=> 'publish', 'cat'=> $id, ) ); $output = ''; if ( $posts ) { $output .= '< p> '; foreach ( $posts as $post ) { $output .= apply_filters( 'the_title', $post-> post_title ) . '< br /> '; } $output .= '< /p> '; }return $output; } add_shortcode( 'tytuly', 'tytuly_postow' );

默认情况下, 偏移量为0, 因此你无需将其添加为参数。我已将posts_per_page设置为-1。这意味着获得全部。
由于你只是列出标题, 因此按标题排序可能很有意义。目前, 它们将按降序排列。
我将输出设置为空字符串, 并在最后返回输出。这意味着无论发生什么情况, 即使短代码正好是一个空字符串, 短代码也将始终返回某些内容。
然后, 我正在检查是否找到帖子。如果是这样, 我要在foreach之前和之后添加一个段落标签。这是为了匹配你的原始代码。
最后, 它循环遍历每个帖子, 并在帖子标题上使用the_title过滤器, 然后以一个break标签结束每个标题。
#2通过查看Shortcode API和add_shortcode函数参考, 可以检查add_shortcode函数的参数是$ tag和$ func。因此, 要开始修复你的代码, 你需要对其进行修复:
//[tutuly] function tytuly_postow($atts) { ... } add_shortcode('tytuly', 'tytuly_postow');

这样, 你将为你的短代码提供一个工作结构。现在, 你的第二个错误是你的函数需要返回一个值, 这就是你的短代码将转换为的值。为此, 你需要使用return。
编辑:另外, 你检索帖子名称的逻辑是错误的, 因此我将其修复:
因此, 你的固定代码如下所示:
//[tutuly id="1"] function tytuly_postow($atts) { extract(shortcode_atts(array( 'id' => 1, ), $atts)); $args = array( 'posts_per_page' => -1, 'category'=> $id, 'post_status'=> 'publish' ); $myposts = get_posts($args); if ($myposts) { $q = '< p> '; foreach ($myposts as $post) { $q .= apply_filters('the_title', $post-> post_title) . '< br /> '; } $q .= '< /p> '; } else { $q = ''; }return $q; } add_shortcode('tytuly', 'tytuly_postow');

现在将posts_per_page设置为-1以检索所有帖子, post_status仅用于检索已发布的帖子。
如果要检索文章的链接, 而不仅仅是名称, 可以更改以下行:
$ q。= apply_filters(‘ the_title’ , $ post-> post_title)。 ‘ < br /> ’ ;
to
$ q。='< a href =http://www.srcmini.com/’ 。 get_permalink($ post-> ID)。 ‘ > ’ apply_filters(‘ the_title’ , $ post-> post_title)。 ‘ < /a> < br /> ’ ;
【列出特定类别的帖子标题的短代码】请注意, 如果你没有足够的编程技能, 则可以始终使用很棒的GenerateWP Shorcodes Generator。

    推荐阅读