What I want
如果使用WordPress中的“菜单”工具将“类别”添加到菜单中,我希望我的主题自动添加一个子菜单,其中包含指向该类别中所有帖子的链接。
<ul>
<li><a href="link">Page 1</a></li>
<li><a href="link">Page 2</a></li>
<li><a href="link">Category X</a>
//Automatically insert list of links to all posts in Category X
<ul>
<li><a href="link">Post 1</a></li>
<li><a href="link">Post 2</a></li>
</ul>
</li>
<li><a href="link">Category Y</a>
//Automatically insert list of links to all posts in Category Y
<ul>
<li><a href="link">Post 1</a></li>
<li><a href="link">Post 2</a></li>
<li><a href="link">Post 3</a></li>
<li><a href="link">Post 4</a></li>
</ul>
</li>
</ul>
What I\'ve tried
在我的
functions.php
我创建了一个函数并将其连接到
walker_nav_menu_start_el
行动通过
$item
变量输入到函数中,我能够识别当前菜单项是否为类别以及它是什么类别。但我在为该类别中的所有帖子创建带有帖子标题的链接列表时遇到了问题。
起初我想我可以用get_posts
函数和foreach循环,但因为我没有输出,所以我只是构建一个输出变量,以传递回walker_nav_menu_start_el
操作,它只是输出当前帖子的详细信息,而不是它循环通过的每个帖子的详细信息。这是我尝试的代码:
function hw_submenu( $output, $item ) {
if( $item->object == \'category\' ) {
$hw_output = \'<ul>\';
$subposts = get_posts( array(
\'posts_per_page\' => -1,
\'category\' => $item->object_id
) );
if ( $subposts ) {
foreach ( $subposts as $post ) :
setup_postdata( $post );
$hw_output .= "<li><a href=\'" . the_permalink() . "\'\'>" . the_title(\'\', \'\', false) . "</a></li>";
endforeach;
wp_reset_postdata();
}
$output .= $hw_output . "</ul>";
}
return $output;
}
add_action( \'walker_nav_menu_start_el\', \'hw_submenu\', 10, 2);
这是一个示例菜单输出:
<ul>
<li><a href="link">Page 1</a></li>
<li><a href="link">Page 2</a></li>
<li><a href="link">Category X</a>
//Automatically inserts list of links to the post I\'m currently viewing
<ul>
<li><a href="link">Post I\'m currently viewing</a></li>
<li><a href="link">Post I\'m currently viewing</a></li>
</ul>
</li>
<li><a href="link">Category Y</a>
//Automatically inserts list of links to the post I\'m currently viewing
<ul>
<li><a href="link">Post I\'m currently viewing</a></li>
<li><a href="link">Post I\'m currently viewing</a></li>
<li><a href="link">Post I\'m currently viewing</a></li>
<li><a href="link">Post I\'m currently viewing</a></li>
</ul>
</li>
</ul>
如何让每个类别在菜单中列出其帖子?我能用这个动作钩吗?或者我应该看一个定制的步行者?