在帖子创建和更新时从自定义字段分配类别

时间:2019-04-09 作者:butterchikita

我正在尝试挂接save\\u post,以便在post更新和创建时自动分配一个类别(来自自定义字段)。基本上,如果日期事件是2020年10月10日,我想将事件分配到“2020”类别。

到目前为止,它部分工作,因为我实际上必须按两次“更新”按钮才能工作。我现在在这里被绊住了。由于使用PHP或WP向导效率不高,我已经尽可能地编写文档。

如果有帮助,我还可以在此处查看调试日志:https://pastebin.com/HQ9B6JqZ?fbclid=IwAR1Ag9_yekNMByN4Dim3BZPJ6ALdIPwQ77hP36W5Ht13QekpkuaofuoLlzY

<?php
/**
 * Create or update category for each event creation or udate
 *
 * @param int $post_id The post ID.
 * @param post $post The post object.
 * @param bool $update Whether this is an existing post being updated or not.
 */
function save_event( $post_id, $post, $update ) {
    $id = $post_id;

    // If this isn\'t a \'book\' post, don\'t do anything.
    $post_type = get_post_type($post_id);
    if ( "event" != $post_type ) return;

    // Check if year has been defined
    $date = get_field(\'event_date\', $post_id, false);
    if (empty($date)) {
        write_log( "Event date is not defined yet" );
        return;
    }

    // Extract event\'s year 
    $date = new DateTime($date);
    $year = $date->format(\'Y\');


    // Get existing category
    $current_cats = get_the_category($post_id);
    if ( ! empty( $current_cats ) ) {
        $current_cat_name = esc_html( $current_cats[0]->name ); 
        write_log( "Current category in use : {$current_cat_name}");

        if ( ! empty($current_cat_name) && $year === $current_cat_name) {
        write_log( "Matching existing category with event date");
        return;
        }
    } 

    // Does the category exist? Should we create it?
    $category_id = get_cat_ID($year);
    if ( $category_id === 0) {
        $category_id = wp_create_category( $year );
        write_log( "Creating category : ({$year}) with ID of {$category_id}");
    } else {
        write_log( "Found category ({$year}) with ID of {$category_id}");
    }

    // Assign the category
    $event_categories = array($category_id);
    $post_categories = wp_set_post_categories( $id, $event_categories);
    write_log( "A new category ({$year} - {$category_id} )  has been assigned to post {$id}");
    write_log( json_encode($post_categories) );

}
add_action( \'save_post\', \'save_event\', 10, 3 );

2 个回复
SO网友:Ravi Singh

获取年份后,您可以使用检查类别是否存在

category_exists($cat_name);
如果未找到,则使用创建类别

 wp_create_category( $cat_name, $parent );
之后,您可以使用

$my_post = array(
  \'post_title\'    => wp_strip_all_tags( $_POST[\'post_title\'] ),
  \'post_content\'  => $_POST[\'post_content\'],
  \'post_status\'   => \'publish\',
  \'post_author\'   => 1,
  \'post_category\' => array( 8,39 )
);

// Insert the post into the database
wp_insert_post( $my_post );
您还可以使用向现有帖子添加类别

wp_set_post_categories($post_id,$post_categories)
更多信息:
https://developer.wordpress.org/reference/functions/wp_insert_post/https://codex.wordpress.org/Function_Reference/wp_create_categoryhttps://developer.wordpress.org/reference/functions/category_exists/

SO网友:butterchikita

所以我试着用set_object_terms()代替wp_set_post_categories(),但基本上是一样的。

我已经尝试转储了几乎所有我可以转储的内容:-$post\\u id和$post object始终可用-post数据有时无法通过$\\u post获得(见下文)

我意识到我不能总是通过使用get\\u field(\'event\\u date\')或$\\u POST[\'acf\'][\'field\\u 5c766105f364e\']来获取我的值,但我发现get\\u field(\'event\\u date\',$POST\\u id)始终返回正确的值。

现在真正奇怪的是,save\\u post()在每次“更新”单击时都会触发三次。。日志告诉我第二次成功了。其他人告诉我,该类别已分配给正确的类别。

所以它实际上是有效的,但我没有任何线索说明原因:-钩子被触发三次-后端编辑页面不反映更新的类别(在第一次单击时)

日志https://pastebin.com/dF2Q15Y0