web-dev-qa-db-fra.com

Ajouter par programmation des termes à des types d'articles personnalisés

Ce que je veux faire, c'est assigner un terme hiérarchique à un type de publication personnalisé:

function create_frontles_posts() {
  $x = 1;

  do {
    $post_id = wp_insert_post(array(
        'comment_status'  =>  'closed',
        'ping_status'   =>  'closed',
        'post_author'   =>  1,
        'post_name'   =>  'Tile'.$x,
        'post_title'    =>  'Tile',
        'post_status'   =>  'publish',
        'post_type'   =>  'frontiles',
      ));
wp_set_object_terms($post_id, array('mosaic-home'), 'tiles_categories', true);


    $x++;
  } while ($x <= 24);
}

Je parviens à créer automatiquement ces 24 messages personnalisés, mais je ne trouve aucun moyen de leur attribuer le terme dans ce processus. Avant, j'avais créé le terme avec cette fonction, sans problème:

function example_insert_category() {
  wp_insert_term(
    'Mosaic - Home',
    'tiles_categories',
    array(
      'description' => 'Add Tiles here to load in first term',
      'slug'    => 'mosaic-home'
    )
  );
}
  add_action('init','example_insert_category');

Qu'est-ce que je fais mal?

1
Dedalos01

Je découvre le problème et la solution. J'ai débogué le "wp_set_object_terms" en utilisant le message "is_wp_error" et le message "Invalid Taxonomy" (Invalid Taxonomy), puis je me suis aperçu que ce terme n'existait pas lors de la création des publications. Donc, je change le hook en "init" dans la fonction programmatiquement_create_post (), et le tour est joué!

En dessous de cette ligne, le code fonctionne:

    <?php
// TO DO WHEN THEME IS ACTIVATED ///////////////////////
if (isset($_GET['activated']) && is_admin()){

  // 3. Add term "mosaic-home" to custom taxonomy "tiles_categories"
    function example_insert_category() {
      wp_insert_term(
        'Mosaic - Home',
        'tiles_categories',
        array(
          'description' => 'Add Tiles here to load in first term',
          'slug'    => 'mosaic-home'
          )
        );
      }
    add_action('init','example_insert_category');

  // 4. Make loop for creating 24 posts
    function create_frontles_posts() {
      $x = 1;

      do {
        $post_id = wp_insert_post(array(
            'comment_status'  =>  'closed',
            'ping_status'   =>  'closed',
            'post_author'   =>  1,
            'post_name'   =>  'tile'.$x,
            'post_title'    =>  'Tile',
            'post_status'   =>  'publish',
            'post_type'   =>  'frontiles',
            // 'tax_input' =>   array('tiles_categories' => 2),
          ));
          wp_set_object_terms($post_id, 'mosaic-home', 'tiles_categories', true);

            $x++;
          } while ($x <= 24);
        }


// 5. add the loop to the function for create posts
  function programmatically_create_post() {

    // Initialize the page ID to -1. This indicates no action has been taken.
    $post_id = -1;
    $title='';
    // If the page doesn't already exist, then create it
    if( null == get_page_by_title( $title ) ) {
        create_frontles_posts();
        } else {
              // Otherwise, we'll stop
              $post_id = -2;
      } 
    } 
    add_filter( 'init', 'programmatically_create_post' );

} // end to do on activation
?>
2
Dedalos01

Voici un exemple. J'ai essayé d'expliquer chaque processus se produisant dans chaque ligne. J'espère que ce code peut facilement vous expliquer comment cela fonctionne.

<?php 
//creating a blank array to store the inserted terms ids
$terms = array();

//inserting the term "Kathmandu" in a custom taxonomy "region"
$tax_insert_id = wp_insert_term('Kathmandu','region' );

//if the term "Kathmandu" is inserted successfully, its term_id is returned and stored in $tax_insert_id
//the returned term_id is pushed in the array $terms
$terms[] = $tax_insert_id['term_id'];

//inserting the term "Banepa" in a custom taxonomy "region"
$tax_insert_id = wp_insert_term('Banepa','region' );

//if the term "Banepa" is inserted successfully, its term_id is returned and stored in $tax_insert_id
//the returned term_id is pushed in the array $terms
$terms[] = $tax_insert_id['term_id'];

//Creating a post array
$post = array(
    'post_title'      => 'Title',
    'post_content'      => 'This is a dummy text',
    'post_status'    => 'publish',
    'post_type'      => 'post',
);

//Inserting the post in WordPress using wp_insert_post()
//if the post is successfully posted, post_id is returned and stored in $the_post_id
$the_post_id = wp_insert_post( $post );

//assign the terms stored in $terms array to $the_post_id post
wp_set_post_terms( $the_post_id, $terms, 'region' );
0
Karun