您可能熟悉 WordPress 中的类别小部件。最近,我们的一位读者问我们是否也可以在下拉菜单中显示最近的帖子。在本文中,我们将向您展示如何在 WordPress 中以下拉列表形式显示最近的帖子。

为什么以及谁需要下拉列表中的最新帖子?
WordPress 附带一个内置的最近帖子小部件,您可以将其添加到任何侧边栏或小部件就绪区域。
该小部件仅显示最近帖子的列表,您可以选择要显示的帖子数量。但如果您想显示超过 5-10 个帖子,那么该列表将占用侧边栏中的大量空间。
一些 WordPress 用户可能需要一种紧凑的方式来显示最近的帖子。在这种情况下,使用下拉列表或可折叠列表可以帮助您节省空间。
让我们看一下在 WordPress 中将最近的帖子显示为下拉菜单的几种不同方法。
在普通下拉菜单中显示 WordPress 最近的帖子(手动代码)
该方法使用内置wp_get_recent_posts
函数。您所需要做的就是将以下代码复制并粘贴到主题的functions.php文件或特定于站点的插件中。
1234567891011121314151617 号18192021 | function wpb_recentposts_dropdown() { $string .= '<select id= "rpdropdown" > <option value= "" selected>Select a Post</option>'; $args = array ( 'numberposts' => '5' , 'post_status' => 'publish' ); $recent_posts = wp_get_recent_posts( $args ); foreach ( $recent_posts as $recent ){ $string .= '<option value="' . get_permalink( $recent ["ID "]) . '" >' . $recent [ "post_title" ]. '</option> ' ; } $string .= '</select> <script type= "text/javascript" > var urlmenu = document.getElementById( "rpdropdown" ); urlmenu.onchange = function () { window.open( this.options[ this.selectedIndex ].value, "_self" ); }; </script>'; return $string ; } add_shortcode( 'rp_dropdown' , 'wpb_recentposts_dropdown' ); add_filter( 'widget_text' , 'do_shortcode' ); |
由
现在您可以在 WordPress 帖子、页面和文本小部件中使用短代码。 [rp_dropdown]
它看起来像这样:

使用插件添加可折叠的最近帖子
上述方法只是以下拉形式列出您最近的帖子。另一种节省空间的方法是添加最近帖子的可折叠列表,当用户单击它时该列表会展开。
您需要做的第一件事是安装并激活Collapse-O-Matic插件。它开箱即用,无需您配置任何设置。
该插件仅允许您使用简码在可折叠菜单中显示任何内容。
在使用这个插件之前,我们需要一种方法来轻松地在我们想要的任何地方显示最近的帖子。只需将此代码添加到主题的functions.php文件或特定于站点的插件中即可。
12345678910111213 | function wpb_recentposts() { $string .= '<ul>' ; $args = array ( 'numberposts' => '5' , 'post_status' => 'publish' ); $recent_posts = wp_get_recent_posts( $args ); foreach ( $recent_posts as $recent ){ $string .= '<li><a href="' . get_permalink( $recent ["ID "]) . '" >' . $recent [ "post_title" ]. '</a></li> ' ; } $string .= '</ul>' ; return $string ; } add_shortcode( 'recentposts' , 'wpb_recentposts' ); add_filter( 'widget_text' , 'do_shortcode' ); |
由
此代码仅允许您使用短代码显示最近帖子的列表[recentposts]
。
现在,我们将在 Collapse-O-Matic 短代码中添加我们的短代码,以创建最近帖子的可折叠列表。
只需添加这样的短代码:
[expand title="Recent Posts"][recentposts][/expand]
您可以将此短代码添加到 WordPress 网站上的文本小部件、帖子或页面中。这就是它在我们的测试站点上的样子。

就这样,我们希望这篇文章能帮助您在 WordPress 中以下拉菜单显示最近的帖子。您可能还想了解在 WordPress 中创建杀手级编辑日历的 6 个技巧。