您是否知道WordPress允许您使用粘性帖子功能来展示您的…
您可能熟悉WordPress中的Category小部件。最近,一位读者问我们是否也可以在下拉列表中显示最近的帖子。在本文中,我们将向您展示如何以WordPress的下拉列表形式显示最近的帖子。

为什么以及谁需要下拉列表中的最新帖子?
WordPress带有一个内置的最新帖子小部件,您可以将其添加到任何侧栏或小部件就绪区域。
该小部件仅显示最近发布的列表,您可以选择要显示的发布数量。但是,如果您想显示5-10个以上的帖子,则该列表将在边栏中占用大量空间。
一些WordPress用户可能需要一种紧凑的方式来显示最新帖子。在这种情况下,使用下拉列表或可折叠列表可以帮助您节省空间。
让我们看一下几种不同的方式来显示最近的帖子作为WordPress中的下拉菜单。
在普通的下拉菜单中显示WordPress最近的帖子(手动代码)
此方法使用内置wp_get_recent_posts
功能。您需要做的就是将以下代码复制并粘贴到主题的functions.php文件或特定于站点的插件中。
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文件或特定于站点的插件中即可。
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'
);
此代码仅允许您使用shortcode显示最近发布的列表[recentposts]
。
现在,我们将我们的简码添加到Collapse-O-Matic简码中,以创建可折叠的近期帖子列表。
只需添加如下的简码:
[expand title="Recent Posts"][recentposts][/expand]
您可以将此短代码添加到WordPress网站上的文本小部件,帖子或页面中。这就是我们测试站点上的样子。