web-dev-qa-db-fra.com

Appeler le contenu d'une page en AJAX dans Wordpress

En dehors de Wordpress, j'ai créé une page d'index simple qui appelle le contenu de 10 autres pages grâce à AJAX. Maintenant, je dois mettre cela dans Wordpress et les appels AJAX ne fonctionnent pas du tout.

J'ai créé la page d'accueil et 10 autres pages. Lorsque l'utilisateur arrive sur mon site Web, la page d'accueil comporte un menu. Chaque élément de ce menu a un lien avec le HREF relatif à l'une des 10 pages (grâce à get_permalink (page_id);). Mon script obtient la valeur du HREF et essaie de charger le contenu de la page. J'ai travaillé sur Wordpress, mais pas à l'intérieur de Wordpress.

Voici le menu :

<ul class="nav">
    <li><a href="<?php echo get_permalink( 41 ); ?>" data-parallax><span class="accessibility">Règle #</span><span class="number">0</span><span class="accessibility"> -</span><span class="rule-label">La coparentalité</span></a></li>
    <li><a href="<?php echo get_permalink( 43 ); ?>" data-parallax><span class="accessibility">Règle #</span><span class="number">1</span><span class="accessibility"> -</span><span class="rule-label">N’obligez pas votre enfant à faire un choix</span></a></li>
    <li><a href="<?php echo get_permalink( 45 ); ?>" data-parallax><span class="accessibility">Règle #</span><span class="number">2</span><span class="accessibility"> -</span><span class="rule-label">Optez pour un discours positif</span></a></li>
    <li><a href="<?php echo get_permalink( 49 ); ?>" data-parallax><span class="accessibility">Règle #</span><span class="number">3</span><span class="accessibility"> -</span><span class="rule-label">Épargnez les détails à votre enfant</span></a></li>
    <li><a href="<?php echo get_permalink( 51 ); ?>" data-parallax><span class="accessibility">Règle #</span><span class="number">4</span><span class="accessibility"> -</span><span class="rule-label">Ne faites pas de votre enfant votre messager</span></a></li>
    <li><a href="<?php echo get_permalink( 53 ); ?>" data-parallax><span class="accessibility">Règle #</span><span class="number">5</span><span class="accessibility"> -</span><span class="rule-label">Détachez-vous de votre ex-conjoint</span></a></li>
    <li><a href="<?php echo get_permalink( 55 ); ?>" data-parallax><span class="accessibility">Règle #</span><span class="number">6</span><span class="accessibility"> -</span><span class="rule-label">Fixez des limites et des attentes pour vos enfants</span></a></li>
    <li><a href="<?php echo get_permalink( 57 ); ?>" data-parallax><span class="accessibility">Règle #</span><span class="number">7</span><span class="accessibility"> -</span><span class="rule-label">Restez ouvert à la communication</span></a></li>
    <li><a href="<?php echo get_permalink( 59 ); ?>" data-parallax><span class="accessibility">Règle #</span><span class="number">8</span><span class="accessibility"> -</span><span class="rule-label">Devenez adulte et responsable</span></a></li>
    <li><a href="<?php echo get_permalink( 61 ); ?>" data-parallax><span class="accessibility">Règle #</span><span class="number">9</span><span class="accessibility"> -</span><span class="rule-label">Mettez votre enfant en confiance et en sécurité</span></a></li>
    <li><a href="<?php echo get_permalink( 63 ); ?>" data-parallax><span class="accessibility">Règle #</span><span class="number">10</span><span class="accessibility"> -</span><span class="rule-label">Apprenez à rebondir !</span></a></li>
</ul>

Dans function.php, j'ai ça:

/******************************************* ****************************/
/* JS 
/******* ************************************************* ***************/
 
 function load_my_scripts () {
 
 // Inclure l'un de mes fichiers javascript personnalisés 
 wp_register_script ('scrollTo', get_stylesheet_directory_uri (). '/ js/jquery.scrollTo-min.js', array ('jquery'), filemtime (get_stylesheet_directory (). ', .js '), true); 
 wp_register_script (' seo-parallaxe ', get_stylesheet_directory_uri ().'/js/jquery.seo-parallax.js ', tableau (' jquery '), filemtime (get_stylesheet_directory) . '/ js/jquery.seo-parallax.js'), true); 
 wp_register_script ('myscript', get_stylesheet_directory_uri (). '/ js/scripts.js', array ('jquery'), filemtime (get_stylesheet_directory (). '/ js/scripts.js'), true); 
 
 wp_enqueue_script ('scrollTo'); 
 wp_enqueue_script ('seo-parallax'); .____.] wp_enqueue_script ('myscript'); 
} 
 add_action ('wp_enqueue_scripts', 'load_my_scripts'); 

Dans jquery.seo-parallax, j'ai ceci:

(function( $ ) {
  $.fn.SEOParallax = function() {
        var container_id = "content"; // the id of the container (must be the same on each page)
        var container = $("#"+container_id); // the container where the content will be put in
        var pages = $("a[data-parallax]"); // every content that should be injected
        var number = 0;
        // console.log(number);
        $(container).html("");
        pages.each(function(page){
            var page = $(this);

            var url = $(this).attr("href");
            console.log(url);
            // Remove the current content
            $.get(url, function(data) {
                // console.log(url);
                var code = $(data);
                code.each(function() {
                    if($(this).attr("id") == container_id){
                        subcontainer = $("<span id='rule-photo-"+number+"-anchor' class='rule-anchor'></span>")
                        $(subcontainer).appendTo($(container));
                        $($(this).html()).insertAfter($(subcontainer));
                        $(page).attr("href", "#rule-photo-"+number+"-anchor");
                        number += 1;

                    } 
                })
            });
        });
            // wrap the content and include it in the page

        // end
  };
})( jQuery );

Dans scripts.js, j'ai ça:

; (function ($) {
 $ ("body") .SEOParallax (); 
 
 $ ("body") .delegate ("a" , "click", function () {
 $ ('html, body') .animate ({
 scrollTop: $ ($ (this) .attr ("href")) .offset ( ) .top 
}, 1200); 
 return false; 
}); 
}) (jQuery || {}); 

Donc, normalement, lorsque la page est chargée, le script seo-parallax prend les 11 liens qui se trouvent dans la navigation, vide le contenu de la page en cours et ajoute le contenu dans le contenu de chaque page. Sur chrome, le contenu n'est pas dans le bon ordre. Normalement, y doit placer le contenu dans cet ordre: 0-1-2-3-4-5-6-7-8-9-10. Mais au lieu de cela, il est placé au hasard (exemple: 1-4-0-9-6-10-2-5-8-3-7).

UPDATE: J'ai appelé <?php var_dump($GLOBALS['wp_query']) ?> juste avant <?php get_footer(); ?>, voici ce que j'ai:

object(WP_Query)#23 (47) { ["query_vars"]=> array(55) { ["error"]=> string(0) "" ["m"]=> int(0) ["p"]=> string(2) "41" ["post_parent"]=> string(0) "" ["subpost"]=> string(0) "" ["subpost_id"]=> string(0) "" ["attachment"]=> string(0) "" ["attachment_id"]=> int(0) ["name"]=> string(0) "" ["static"]=> string(0) "" ["pagename"]=> string(0) "" ["page_id"]=> string(2) "41" ["second"]=> string(0) "" ["minute"]=> string(0) "" ["hour"]=> string(0) "" ["day"]=> int(0) ["monthnum"]=> int(0) ["year"]=> int(0) ["w"]=> int(0) ["category_name"]=> string(0) "" ["tag"]=> string(0) "" ["cat"]=> string(0) "" ["tag_id"]=> string(0) "" ["author_name"]=> string(0) "" ["feed"]=> string(0) "" ["tb"]=> string(0) "" ["paged"]=> int(0) ["comments_popup"]=> string(0) "" ["meta_key"]=> string(0) "" ["meta_value"]=> string(0) "" ["preview"]=> string(0) "" ["s"]=> string(0) "" ["sentence"]=> string(0) "" ["fields"]=> string(0) "" ["category__in"]=> array(0) { } ["category__not_in"]=> array(0) { } ["category__and"]=> array(0) { } ["post__in"]=> array(0) { } ["post__not_in"]=> array(0) { } ["tag__in"]=> array(0) { } ["tag__not_in"]=> array(0) { } ["tag__and"]=> array(0) { } ["tag_slug__in"]=> array(0) { } ["tag_slug__and"]=> array(0) { } ["ignore_sticky_posts"]=> bool(false) ["suppress_filters"]=> bool(false) ["cache_results"]=> bool(false) ["update_post_term_cache"]=> bool(true) ["update_post_meta_cache"]=> bool(true) ["post_type"]=> string(0) "" ["posts_per_page"]=> int(10) ["nopaging"]=> bool(false) ["comments_per_page"]=> string(2) "50" ["no_found_rows"]=> bool(false) ["order"]=> string(4) "DESC" } ["tax_query"]=> object(WP_Tax_Query)#43 (2) { ["queries"]=> array(0) { } ["relation"]=> string(3) "AND" } ["meta_query"]=> object(WP_Meta_Query)#42 (2) { ["queries"]=> array(0) { } ["relation"]=> NULL } ["post_count"]=> int(1) ["current_post"]=> int(-1) ["in_the_loop"]=> bool(false) ["comment_count"]=> int(0) ["current_comment"]=> int(-1) ["found_posts"]=> int(0) ["max_num_pages"]=> int(0) ["max_num_comment_pages"]=> int(0) ["is_single"]=> bool(false) ["is_preview"]=> bool(false) ["is_page"]=> bool(true) ["is_archive"]=> bool(false) ["is_date"]=> bool(false) ["is_year"]=> bool(false) ["is_month"]=> bool(false) ["is_day"]=> bool(false) ["is_time"]=> bool(false) ["is_author"]=> bool(false) ["is_category"]=> bool(false) ["is_tag"]=> bool(false) ["is_tax"]=> bool(false) ["is_search"]=> bool(false) ["is_feed"]=> bool(false) ["is_comment_feed"]=> bool(false) ["is_trackback"]=> bool(false) ["is_home"]=> bool(false) ["is_404"]=> bool(false) ["is_comments_popup"]=> bool(false) ["is_paged"]=> bool(false) ["is_admin"]=> bool(false) ["is_attachment"]=> bool(false) ["is_singular"]=> bool(true) ["is_robots"]=> bool(false) ["is_posts_page"]=> bool(false) ["is_post_type_archive"]=> bool(false) ["query_vars_hash"]=> string(32) "8f15f3752a526b936a323e2a33ace1e5" ["query_vars_changed"]=> bool(false) ["thumbnails_cached"]=> bool(false) ["query"]=> array(0) { } ["request"]=> string(143) "SELECT wp_4_posts.* FROM wp_4_posts WHERE 1=1 AND wp_4_posts.ID = 41 AND wp_4_posts.post_type = 'page' ORDER BY wp_4_posts.post_date DESC " ["posts"]=> &array(1) { [0]=> object(stdClass)#62 (25) { ["ID"]=> int(41) ["post_author"]=> string(1) "7" ["post_date"]=> string(19) "2013-03-20 11:06:49" ["post_date_gmt"]=> string(19) "2013-03-20 11:06:49" ["post_content"]=> string(0) "" ["post_title"]=> string(38) "La coparentalité, comment ça marche?" ["post_excerpt"]=> string(0) "" ["post_status"]=> string(7) "publish" ["comment_status"]=> string(4) "open" ["ping_status"]=> string(6) "closed" ["post_password"]=> string(0) "" ["post_name"]=> string(34) "la-coparentalite-comment-ca-marche" ["to_ping"]=> string(0) "" ["pinged"]=> string(0) "" ["post_modified"]=> string(19) "2013-03-20 14:29:31" ["post_modified_gmt"]=> string(19) "2013-03-20 14:29:31" ["post_content_filtered"]=> string(0) "" ["post_parent"]=> int(0) ["guid"]=> string(43) "http://miniguide.wp.2houses.com/?page_id=41" ["menu_order"]=> int(0) ["post_type"]=> string(4) "page" ["post_mime_type"]=> string(0) "" ["comment_count"]=> string(1) "0" ["ancestors"]=> array(0) { } ["filter"]=> string(3) "raw" } } ["post"]=> object(stdClass)#62 (25) { ["ID"]=> int(41) ["post_author"]=> string(1) "7" ["post_date"]=> string(19) "2013-03-20 11:06:49" ["post_date_gmt"]=> string(19) "2013-03-20 11:06:49" ["post_content"]=> string(0) "" ["post_title"]=> string(38) "La coparentalité, comment ça marche?" ["post_excerpt"]=> string(0) "" ["post_status"]=> string(7) "publish" ["comment_status"]=> string(4) "open" ["ping_status"]=> string(6) "closed" ["post_password"]=> string(0) "" ["post_name"]=> string(34) "la-coparentalite-comment-ca-marche" ["to_ping"]=> string(0) "" ["pinged"]=> string(0) "" ["post_modified"]=> string(19) "2013-03-20 14:29:31" ["post_modified_gmt"]=> string(19) "2013-03-20 14:29:31" ["post_content_filtered"]=> string(0) "" ["post_parent"]=> int(0) ["guid"]=> string(43) "http://miniguide.wp.2houses.com/?page_id=41" ["menu_order"]=> int(0) ["post_type"]=> string(4) "page" ["post_mime_type"]=> string(0) "" ["comment_count"]=> string(1) "0" ["ancestors"]=> array(0) { } ["filter"]=> string(3) "raw" } ["queried_object"]=> object(stdClass)#62 (25) { ["ID"]=> int(41) ["post_author"]=> string(1) "7" ["post_date"]=> string(19) "2013-03-20 11:06:49" ["post_date_gmt"]=> string(19) "2013-03-20 11:06:49" ["post_content"]=> string(0) "" ["post_title"]=> string(38) "La coparentalité, comment ça marche?" ["post_excerpt"]=> string(0) "" ["post_status"]=> string(7) "publish" ["comment_status"]=> string(4) "open" ["ping_status"]=> string(6) "closed" ["post_password"]=> string(0) "" ["post_name"]=> string(34) "la-coparentalite-comment-ca-marche" ["to_ping"]=> string(0) "" ["pinged"]=> string(0) "" ["post_modified"]=> string(19) "2013-03-20 14:29:31" ["post_modified_gmt"]=> string(19) "2013-03-20 14:29:31" ["post_content_filtered"]=> string(0) "" ["post_parent"]=> int(0) ["guid"]=> string(43) "http://miniguide.wp.2houses.com/?page_id=41" ["menu_order"]=> int(0) ["post_type"]=> string(4) "page" ["post_mime_type"]=> string(0) "" ["comment_count"]=> string(1) "0" ["ancestors"]=> array(0) { } ["filter"]=> string(3) "raw" } ["queried_object_id"]=> int(41) }

Où est le problème ? Merci

2
Cédric Charles

J'ai déjà mentionné dans les commentaires que il existe des méthodes préférées pour charger vos scripts . Le plus important est de définir les dépendances et l’utilisation des hooks appropriés.

La partie suivante ne fonctionnera pas comme ceci:

$(document).ready(function() {
    $("body").SEOParallax();

    $("body").delegate("a", "click", function() {
        $('html, body').animate({
            scrollTop: $($(this).attr("href")).offset().top
        }, 1200);
        return false;
    });
});

Les Les normes de codage Javascript WordPress de Tom McFarlin vous montrent la bonne façon de le faire - en évitant de recourir au mode sans conflit:

;( function ($) {
    // ...
} ( jQuery ) );

Il s’agit d’une fonction qui invoque elle-même et s’exécute immédiatement en injectant jQuery comme premier argument, qui porte le nom $ inside la portée de la fonction elle-même. Maintenant, vous pouvez utiliser en toute sécurité $ au lieu de jQuery.

Donc, votre script devrait ressembler à ceci:

;( function($) {
    $( "body" ).SEOParallax();

    $( "body" ).delegate( "a", "click", function() {
        $( 'html, body' ).animate( {
            scrollTop: $( $( this ).attr( "href" ) ).offset().top
        }, 1200 );
        return false;
    } );
} )( jQuery || {} );

Je devrais également noter que vous ne devriez plus utiliser .delegate(). Citation de jQuery:

"A partir de jQuery 1.7, la méthode alternative .on() peut être utilisée à la place de .delegate()"

mais cela fait partie d'une autre discussion qu'il vaut mieux déplacer sur StackOverflow.

3
kaiser

Vous pourriez envisager d'utiliser djax , qui est dynamique pjax (et pjax étant ajax à l'aide de pushState).

pjax (et par extension djax) vous permet de définir un conteneur sur la page qui existe dans toutes les autres pages, par exemple un <div id="content">. Vous ajoutez simplement une classe que vous définissez également dans le code JavaScript du plugin. Par exemple: <div id="content" class="dynamic">.

Ce plugin tente maintenant de charger le code HTML de l'URL demandée, recherche l'élément avec la classe dynamic et remplace le contenu de la page actuelle de cet élément par le résultat récupéré.

djax était une pjax- modification spécialement conçue pour WordPress, et je l’utilise avec succès sur http://www.tjoonz.com (si vous souhaitez voir un exemple de travail).

1
Marc Dingena