>我创建了一个简单的自定义插件,将帖子分组为类别:
function custom_category_loop()
{
// Grab all the categories from the database that have posts.
$categories = get_terms( 'category', 'orderby=name&order=ASC');
// Loop through categories
foreach ( $categories as $category )
{
// Display category name
echo '<h2 class="post-title">' . $category->name . '</h2>';
echo '<div class="post-list">';
// WP_Query arguments
$args = array(
'cat' => $category->term_id,
'orderby' => 'term_order',
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() )
{
while ( $query->have_posts() )
{
$query->the_post();
?>
<div><a href="<?php the_permalink();?>"><?php the_title(); ?></a></div>
<?php
} // End while
} // End if
echo '</div>';
// Restore original Post Data
wp_reset_postdata();
} // End foreach
}
add_shortcode( 'my_posts_grouped', 'custom_category_loop' );
然后我创建了一个页面并添加了单行
[my_posts_grouped]
我的WordPress安装是一个多站点安装,所有页面都使用相同的主题,因为我有相同的网站,但语言(和URL)不同。
我的问题是,在我的所有网站上,除了一个网站,简码都完美地工作。仅在一个站点上,代码在标题之前和正文页面内输出。
任何想法为什么以及如何解决这个问题?
代码必须返回数据(而不是使用echo
或类似方法直接打印到屏幕上)。
从文档中:
请注意,短代码调用的函数不应产生任何类型的输出。简码函数应返回用于替换短码的文本。直接生成输出将导致意外结果。这类似于筛选器函数的行为方式,因为它们不应从调用中产生预期的副作用,因为您无法控制从何时何地调用它们。
事实上,您的代码仅在一个网站上而不是所有网站上中断,我会归结为运气。
代码的更新版本,使用 return
而不是多个 echo
调用,这应该可以解决您的问题:
function custom_category_loop()
{
// String to return
$html = '';
// Grab all the categories from the database that have posts.
$categories = get_terms( 'category', 'orderby=name&order=ASC');
// Loop through categories
foreach ( $categories as $category )
{
// Display category name
$html .= '<h2 class="post-title">' . $category->name . '</h2>';
$html .= '<div class="post-list">';
// WP_Query arguments
$args = array(
'cat' => $category->term_id,
'orderby' => 'term_order',
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() )
{
while ( $query->have_posts() )
{
$query->the_post();
$html .= '<div><a href="' . get_permalink() . '">' . get_the_title() . '</a></div>';
} // End while
} // End if
$html .= '</div>';
// Restore original Post Data
wp_reset_postdata();
// Return the HTML string to be shown on screen
return $html;
} // End foreach
}
add_shortcode( 'my_posts_grouped', 'custom_category_loop' );