【问题标题】:change the category of a post before it is saved/published在保存/发布之前更改帖子的类别
【发布时间】:2019-04-30 11:33:21
【问题描述】:

用户创建了一个新的标准帖子。如果他忘记添加他的类别,我希望我的脚本为他添加它。
为了测试这一点,我首先想更改“测试”类别中所有不匹配的帖子类别。

function change_cat($data, $postarr){

    $author_role = "test"; 
    $data["post_category"] = $author_role; // seems not working

    return $data;
}
add_filter("wp_insert_post_data", "change_cat", 99 , 2);

不幸的是,目前该脚本会停止所有帖子和更改。

编辑:不使用设置中的默认选项的原因:我想稍后用不同的角色替换测试。

【问题讨论】:

  • 在 Wordpress 设置中,如果没有选中,您可以设置默认类别。
  • @DanielVickers 感谢您指出这一点。我没有提到我可能想根据角色添加不同的类别。

标签: php wordpress customization


【解决方案1】:

如果未选择标准帖子,如何将帖子类别设置为“测试”

为此,我们必须获取当前帖子 ID 并仅在它是标准帖子且在保存帖子时尚未获得类别时更新类别。

<?php function set_default_category($post_ID){

    if(wp_is_post_autosave($post_ID) || wp_is_post_revision($post_ID)) {
        return;
    } //If this is just an autosave or post revision, don't do anything

    $postFormat = get_post_format( $post_ID ); //Get the post format of current post

    if( !empty( $postFormat ) ) {
        return;
    } //If post is not a standard format, don't do anything

    $currentCat = get_the_category(); //Get the current set Category
    $defaultCat = get_cat_ID( "test" ); //Get ID of "test" category

    if( empty( $currentCat ) ) { //Check if category is set
        wp_set_post_categories( $post_ID, $defaultCat );  //Set the current post ID's Category to "test"
    }

} add_action('save_post', 'set_default_category');?>

这还没有经过测试,但理论上应该可以。如果没有,请告诉我您遇到的任何错误,以便我进行修改。

【讨论】:

    【解决方案2】:

    我认为wp_insert_post_data 中的post_category 应该是数组。查看文档https://developer.wordpress.org/reference/functions/wp_insert_post/

    function book_save( $data, $postarr ) {
        // check what we save before changes
        if ( ! isset($_POST['post_type']) || $_POST['post_type'] != 'post' ) return $data;
        if ( get_current_screen()->id != 'post' ) return $data;
        if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE  ) return $data;
        if ( ! current_user_can('edit_post', $postarr['ID'] ) ) return $data;
    
        // all ok let's check post category
        if ( empty($data['post_category']) ) {
            $data['post_category'] = array(12, 20); // array with category IDs
        }
    
        return $data;
    }
    add_action('wp_insert_post_data', 'book_save', 20, 2 );
    

    【讨论】:

    • 这不检查帖子格式是否标准,也没有关于将所有帖子设置为“测试”的任何内容
    • @daniel-vickers 你能指出蝴蝶15在他的问题中询问的帖子格式吗?
    • “用户创建新的标准帖子”标准是指WordPress中的帖子格式:)
    • codex.wordpress.org/Plugin_API/Filter_Reference/… 中似乎没有给出 $data['post_category'] 只有 $postarr 包含 'post_category' ...
    猜你喜欢
    • 2018-12-20
    • 1970-01-01
    • 1970-01-01
    • 2016-08-10
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    • 1970-01-01
    • 2014-01-16
    相关资源
    最近更新 更多