也想出现在这里?联系我们

WordPress自定义文章类型添加文章置顶功能选项

2024.03.06 wordpress教程
  • 文章介绍
  • 升级版本
  • 评价&建议

要为WordPress自定义文章类型添加文章置顶功能选项,您可以使用以下步骤:

  1. 在主题的 functions.php 文件中添加以下代码,以启用文章置顶功能:
function custom_post_type_support() {
    add_post_type_support( 'your_custom_post_type', 'sticky' );
}
add_action( 'init', 'custom_post_type_support' );

请确保将 'your_custom_post_type' 替换为您实际的自定义文章类型名称。

  1. 接下来,您需要在您的自定义文章类型的编辑页面中添加一个复选框,以便作者可以选择置顶文章。您可以使用以下代码在编辑页面上添加一个复选框:
function add_sticky_checkbox() {
    global $post;
    if ( 'your_custom_post_type' === $post>post_type ) {
        $is_sticky = is_sticky( $post>ID ) ? 'checked' : '';
        echo '<label><input type="checkbox" name="sticky" ' . $is_sticky . ' /> 置顶文章</label>';
    }
}
add_action( 'post_submitbox_misc_actions', 'add_sticky_checkbox' );

确保再次将 'your_custom_post_type' 替换为您的自定义文章类型名称。

  1. 最后,您需要保存复选框的值,并在文章循环中考虑这个值。在您的主题文件中,您可以使用以下代码来保存和显示置顶文章:
function save_sticky_checkbox( $post_id ) {
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) 
        return $post_id;

    if ( isset( $_POST['sticky'] ) && 'your_custom_post_type' === get_post_type( $post_id ) ) {
        if ( $_POST['sticky'] === 'on' ) {
            stick_post( $post_id );
        } else {
            unstick_post( $post_id );
        }
    }
    return $post_id;
}
add_action( 'save_post', 'save_sticky_checkbox' );

再次替换 'your_custom_post_type'。

现在,您的自定义文章类型应该具有文章置顶功能选项。在文章编辑页面中,您可以看到一个复选框,允许您将文章置顶。在文章循环中,您可以检查文章是否置顶,并相应地显示它们。

有用0
  • 2024.03.06初次和大家见面了!

等待您对该主题的建议

发表评论

还能输入240个字

Hi, 欢迎加入Wordpress技术交流群,带你装逼带你飞!

我要入群
也想出现在这里?联系我们
wordpress加速

我来推荐一个更牛逼的给你看看?

  • 猛戳我吧