web-dev-qa-db-fra.com

Enregistrez la taxonomie plus tôt afin qu'elle puisse être utilisée dans functions.php et admin-ajax.php

Ceci est un suivi de ce message , expliquant pourquoi je ne peux pas utiliser la fonction get_terms alors que je suis dans functions.php (en train d'appeler via ajax/admin_ajax.php ).

Je peux saisir les termes (taxe personnalisée) sur n’importe quel message, sur n’importe quelle page, sauf dans ma fonction ajax. Je reçois l'erreur redoutée "La taxonomie n'existe pas" lors du vidage de la valeur de get_terms.

Le problème est que la taxonomie est enregistrée après , j'appelle la fonction pour trouver les termes.

La question est de savoir comment enregistrer la taxe suffisamment tôt pour pouvoir utiliser cette fonction. Mon code pour enregistrer le type d'article personnalisé et la taxonomie est d'abord dans mon functions.php (inclus via un php externe pour garder les fonctions.php propres)

/************************************************ 
*
* 1.0 ------------------ Events ----------------
*
************************************************/


// 1. Custom Post Type Registration (Events)
add_action( 'init', 'create_event_postype', 0 );

function create_event_postype() {
  $labels = array(
    'name' => _x('Events', 'post type general name'),
    'singular_name' => _x('Event', 'post type singular name'),
    'add_new' => _x('Add New', 'events'),
    'add_new_item' => __('Add New Event'),
    'edit_item' => __('Edit Event'),
    'new_item' => __('New Event'),
    'view_item' => __('View Event'),
    'search_items' => __('Search Events'),
    'not_found' =>  __('No events found'),
    'not_found_in_trash' => __('No events found in Trash'),
    'parent_item_colon' => '',
);

$args = array(
    'label' => __('Events'),
    'labels' => $labels,
    'public' => true,
    'can_export' => true,
    'show_ui' => true,
    '_builtin' => false,
    '_edit_link' => 'post.php?post=%d', // ?
    'capability_type' => 'post',
    'menu_icon' => get_bloginfo('template_url').'/images/icons/events.png',
    'hierarchical' => false,
    'rewrite' => array( "slug" => "events" ),
    'supports'=> array('title', 'thumbnail', 'excerpt', 'editor', 'custom-fields') ,
    'show_in_nav_menus' => true,
    'taxonomies' => array('post_tag', 'tf_eventtype')
);

register_post_type( 'tf_events', $args);

}

// 2. Custom Taxonomy Registration (Event Types)
add_action( 'init', 'create_eventtype_taxonomy', 0 );
function create_eventtype_taxonomy() {

  $labels = array(
    'name' => _x( 'Event Type', 'taxonomy general name' ),
    'singular_name' => _x( 'Event Type', 'taxonomy singular name' ),
    'search_items' =>  __( 'Search Event Types' ),
    'popular_items' => __( 'Popular Event Types' ),
    'all_items' => __( 'All Event Types' ),
    'parent_item' => null,
    'parent_item_colon' => null,
    'edit_item' => __( 'Edit Event Type' ),
    'update_item' => __( 'Update Event Type' ),
    'add_new_item' => __( 'Add New Event Type' ),
    'new_item_name' => __( 'New Event Type Name' ),
    'separate_items_with_commas' => __( 'Separate event types with commas' ),
    'add_or_remove_items' => __( 'Add or remove event types' ),
    'choose_from_most_used' => __( 'Choose from the most used event types' ),
);

register_taxonomy('tf_eventtype','tf_events', array(
    'label' => __('Event Type'),
    'labels' => $labels,
    'hierarchical' => true,
    'show_ui' => true,
    'query_var' => true,
    'rewrite' => array( 'slug' => 'event-type' ),
));
}

Voici un pseudo-code pour montrer comment j'appelle cette fonction

depuis une page personnalisée, j'appelle une fonction via AJAX (ajax-admin.php)

$.ajax({  
            type: "POST",  
            url: "<? bloginfo('url'); ?>/wp-admin/admin-ajax.php", //Built in WP AJAX
            data: data, 
            success:  function(data){
                         //console.log('search complete');
                         $("#event-list").html(data)                                                         
                         }  
    });

Voici la fonction qui appelle une requête personnalisée et où get_terms échoue.

/****************************************************************
*
* 1.0 Calendar AJAX Queries
*
****************************************************************/
// if both logged in and not logged in users can send this AJAX request,
// add both of these actions, otherwise add only the appropriate one
add_action( 'wp_ajax_nopriv_calendar_search', 'calendar_search' );
add_action( 'wp_ajax_calendar_search', 'calendar_search' );

function calendar_search() {        
        $args = array(
            'post_type' => 'tf_events',         
            'post_status' => 'publish',
            'order' => 'ASC'
        );

        $query = new WP_Query( $args ); 

        // - loop start -
        if ( $query->have_posts() ) {

         while ($query->have_posts()) : $query->the_post(); /*Shows the posts that are available. */

                //Event Type
                $cats = get_the_terms($post->ID , 'tf_eventtype'); //the function that fails. All other custom data works fine 

                echo 
                '<article class="post" id="post-'. $post->ID . '"  itemscope itemtype="http://schema.org/Event">                       
                   <time></time>
                   <h2  itemprop="name" class="entry-title"><a href="' . get_permalink() .'">'. get_the_title() . '</a></h2>                
                   <div class="entry">
                     <p itemprop="location">';
                       if($cats) foreach($cats as $cat){ 
                            echo " | " . $cat->name;
                       }
                       echo 
                     "</p>  
                   </div><!--#entry-->
                 </article>";

            endwhile; 
         } else {
            echo "<h2 class='month'>Sorry, no events found!</h2>";            
          } 
        die(); // this is required to return a proper result      

}

1
Nate

Ainsi, grâce à l'aide de G. M., j'ai pu résoudre le problème plus efficacement, maintenant que je savais que init n'était pas appelé. J'ai commencé à supprimer toutes les fonctions superflues de mon fichier functions.php et je me suis rendu compte que j'ai appelé deux fois do_action, car de nombreuses fonctions sont exécutées via admin-ajax.php. Les appels à do_action ne doivent être utilisés qu'une seule fois! Bizarre que le bogue se soit présenté!

$action = isset($_POST['action']) ? $_POST['action'] : null;

//These functions take an ajax call and then call the appropriate PHP function
// this hook is fired if the current viewer is not logged in
do_action( 'wp_ajax_nopriv_' . $action );
do_action( 'wp_ajax_' . $action );
2
Nate

Ajoutez simplement global $post; avant d'utiliser la variable $post:

while ($query->have_posts()) : $query->the_post();
  global $post;
  $cats = get_the_terms($post->ID , 'tf_eventtype');
  //... and so on
0
gmazzap

Le message "taxonomie invalide" apparaît parce que, lorsque l'appel ajax est effectué, toutes les taxonomies n'ont pas été enregistrées car tous les plugins n'ont pas été initialisés.

la solution est de lancer le crochet ajax après l'initialisation et ça marche donc bien

ex.

        add_action( 'init', function() {

            //add the ajax hook only when all the taxonomies have been registered
            add_action('wp_ajax_my_action',  function() {

                $result = get_terms( 'my_taxonomy_name' );
            }

        }, 99);
0
Fabri