WordPress如何自定义文章开启置顶按钮?

无评论

作者照片

By 霜天

WordPerss想制作置顶的功能,结果竟然发现自定义文章类型没有置顶的功能选项,查阅资料后发现WP只是没有显示置顶的选项,功能和文章类型一样。那么WordPress如何自定义文章开启置顶按钮?

添加按钮

首页为自定义文章添加置顶开关按钮。使用add_meta_box钩子添加选项面板,注意修改下面第四个测试为自己的自定义文章类型。

add_action( \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’add_meta_boxes\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’, \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’add_sticky_box\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’ );

function add_sticky_box(){

add_meta_box( \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’product_sticky\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’, __( \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’Sticky\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’ ), \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’product_sticky\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’, \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’sites\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’, \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’side\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’, \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’high\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’ );// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’sites\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’ 改为自己的自定义文章类型

}

function product_sticky (){

echo \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'<div><input id=\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”super-sticky\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\” name=\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”sticky\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\” type=\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”checkbox\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\” value=\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”sticky\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\” \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’. checked( is_sticky(), true, false ) .\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’/> <label for=\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”super-sticky\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\” class=\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”selectit\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”>\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’ .__( \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’Stick this post to the front page\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’ ). \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'</label></div>\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’;

}

将以上代码添加到当前所使用主题的 functions.php 文件中,保存之后新建或编辑某篇自定义文章类型就会在右上角面板(发布之上)中看到置顶功能选项。

使用

有了置顶功能,剩下的就是输出了。其实自定义文章类型的置顶文章跟平常的 post 文章类型的置顶文章输出是一样的操作。比如:

输出置顶文章

$sticky = get_option( \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’sticky_posts\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’ );

query_posts( array( \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’post__in\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’ => $sticky, \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’ignore_sticky_posts\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’ => 1 ) );

不输出置顶文章

$sticky = get_option( \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’sticky_posts\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’ );

query_posts(array(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’ignore_sticky_posts\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’ => 1,\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’post__not_in\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’ => $sticky); );

说明:ignore_sticky_posts 默认值是 0,如果等于 1,意思就是忽略 sticky_posts,会正常输出置顶文章但不会置顶显示。

添加【置顶】标识,以便用户知道这是一篇置顶文章。方法也很简单,只需要在循环语句中的标题后面添加以下代码即可:

<?php if (is_sticky()) {?><span class=\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”sticky-icon\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”>置顶</span><?php } ?>

发表评论