如何在WordPress中实现自定义文章草稿功能?

玖比肆 WordPress 54

描述如何使用WordPress代码实现自定义文章草稿功能的方法和注意事项。

回复

共1条回复 我来回复
  • 玖比肆的头像
    玖比肆 评论

    实现自定义文章草稿功能可以通过创建自定义文章状态来实现。以下是具体步骤:

    步骤 1:创建自定义文章状态

    打开 functions.php 文件并添加以下代码:

    ```
    register_post_status( 'custom-draft', array(
    'label' => _x( 'Custom Draft', 'post' ),
    'public' => false,
    'exclude_from_search' => true,
    'show_in_admin_all_list' => false,
    'show_in_admin_status_list' => true,
    ) );
    ```

    上述代码创建了一个名为 “Custom Draft”(自定义草稿)的文章状态,并将其排除在搜索结果之外。它不会在所有文章列表中显示,但会在发布状态下显示。

    步骤 2:添加自定义文章状态到发布操作

    为了将自定义草稿添加到文章的现有发布选项中,我们需要通过 add_action 函数将其添加到面板上。在 functions.php 文件中添加以下代码:

    ```
    function add_custom_draft_to_post_status_options() {
    global $post;

    if ( $post->post_type == 'post' ) {
    if ( $post->post_status == 'custom-draft' ) {
    echo '';
    } else {
    echo '';
    }
    }
    }

    add_action( 'admin_footer-post.php', 'add_custom_draft_to_post_status_options' );
    add_action( 'admin_footer-post-new.php', 'add_custom_draft_to_post_status_options' );
    ```

    上述代码在文章发布选项中添加了一个名为 “Custom Draft” 的选项。当我们选择该选项时,文章状态将是 “custom-draft”。

    步骤 3:保存自定义状态

    在保存文章时,我们需要确保正确保存自定义状态。为此,我们将使用 save_post 动作。在 functions.php 文件中添加以下代码:

    ```
    function save_custom_draft_status( $post_id, $post ) {

    if ( $post->post_status == 'custom-draft' ) {

    // Update post
    $post->post_status = 'draft';
    wp_update_post( $post );
    }
    }

    add_action( 'save_post', 'save_custom_draft_status', 10, 2 );
    ```

    上述代码确保当一个自定义草稿被保存时,它被保存为普通草稿。

    注意事项:

    - 在创建自定义状态时,请确保将其设置为 “public” => false,以确保被排除在搜索结果之外。
    - 请注意,该方法也可以在自定义文章类型上使用。
    - 在使用此方法时,请记住,在发布之前对帖子进行彻底的测试,以确保所有东西都按预期工作。

    2023年 5月 11日 下午4:39 0条评论
微信客服
分享本页
返回顶部
玖比肆(9Bi4)专注于帮助企业实现数字化转型,提供全方位的网站建设、网络运营、网络推广、网络营销和SEO优化等一系列数字化营销服务。