😅Insert post with custom taxonomy 🌟(ok)

https://wordpress.stackexchange.com/questions/210229/tax-input-not-working-wp-insert-post

Sử dụng wp_insert_post

C:\xampp\htdocs\style2\wp-content\themes\gutener\header.php

<?php  
    $custom_tax = array(
      'subjects' => array(73,72)
    );
    $post = array(
        'post_content' => 'This will be the content.',
        'post_title'   => 'Hello World 1',
        'tax_input'    => $custom_tax
    );
    $post_id = wp_insert_post( $post );
  ?>

C:\xampp\htdocs\style2\wp-content\themes\gutener\functions.php

//create a custom taxonomy name it subjects for your posts
function create_subjects_hierarchical_taxonomy() {
// Add new taxonomy, make it hierarchical like categories
//first do the translations part for GUI
  $labels = array(
    'name' => _x( 'Subjects', 'taxonomy general name' ),
    'singular_name' => _x( 'Subject', 'taxonomy singular name' ),
    'search_items' =>  __( 'Search Subjects' ),
    'all_items' => __( 'All Subjects' ),
    'parent_item' => __( 'Parent Subject' ),
    'parent_item_colon' => __( 'Parent Subject:' ),
    'edit_item' => __( 'Edit Subject' ), 
    'update_item' => __( 'Update Subject' ),
    'add_new_item' => __( 'Add New Subject' ),
    'new_item_name' => __( 'New Subject Name' ),
    'menu_name' => __( 'Subjects' ),
  );    
// Now register the taxonomy
  register_taxonomy('subjects',array('post'), array(
    'hierarchical' => true,
    'labels' => $labels,
    'show_ui' => true,
    'show_in_rest' => true,
    'show_admin_column' => true,
    'query_var' => true,
    'rewrite' => array( 'slug' => 'subject' ),
  ));
}

Sử dụng wp_update_post

C:\xampp\htdocs\style2\wp-content\themes\gutener\header.php

<?php  
    $custom_tax = array(
      'subjects' => array(73,72)
    );
    // $post = array(
    //     'post_content' => 'This will be the content.',
    //     'post_title'   => 'Hello World 1',
    //     'tax_input'    => $custom_tax
    // );
    // $post_id = wp_insert_post( $post );
     $custom_tax = array(
      'subjects' => array(73)
    );
    $my_post = array(
      'ID'           => 2512,
      'post_title'   => 'This is the post title.',
      'post_content' => 'This is the updated content.',
      'tax_input'    => $custom_tax
    );
    // Update the post into the database
    wp_update_post( $my_post );
  ?>

Last updated