Comment obtenir de la maçonnerie et des images chargées pour fonctionner avec WordPress

Publié par Jean-Michel le

Environ 4 heures après les 20 minutes que je pensais qu’il faudrait pour mettre en place la maçonnerie avec de nouveaux thèmes wordpress, j’ai décidé que je ferais mieux de demander de l’aide.

J’ai de la maçonnerie qui fonctionne bien avec des images chargées dans mes sites de maquette html, voici le code html dépouillé.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="imagesloaded.pkgd.min.js"></script>
<script src="masonry.pkgd.min.js"></script>
</head>

<body>

<div class="masonry-container js-masonry"  data-masonry-options='{ "isFitWidth": true }'>

    <div class="block-wrapper">content</div>

    <div class="block-wrapper">content</div>

    <div class="block-wrapper">content</div>

</div><!-- end masonry-container js-masonry -->

<script>
var container = document.querySelector('.masonry-container');
var msnry;
// initialize Masonry after all images have loaded
imagesLoaded( container, function() {
    msnry = new Masonry( container );
});
</script>

</body>
</html>

La question:

Comment faire pour que cela fonctionne avec WordPress ?


Ce que j’ai essayé jusqu’à présent

À peu près tout ce que je pouvais trouver sur les googs. (J’ai compté plus de 40 onglets ouverts en essayant de trouver une réponse) Voici la variation simple avec laquelle j’ai commencé…

dans functions.php (les fonctions n’ont absolument rien d’autre dedans)

function enqueue_masonry() {
    wp_enqueue_script('masonry');
}
add_action('wp_enqueue_scripts','enqueue_masonry');

dans footer.php (images chargées)

<script>
var container = document.querySelector('.masonry-container');
var msnry;
// initialize Masonry after all images have loaded
imagesLoaded( container, function() {
msnry = new Masonry( container );
});
</script>

</body>

dans index.php (également essayé d’initialiser à partir de functions.php au lieu de html)

<div class="masonry-container js-masonry"  data-masonry-options='{ "isFitWidth": true }'>

dans header.php

<?php wp_head(); ?>
</head>

Remarques

  • tous les plugins désactivés
  • c’est un thème parent personnalisé
  • les fonctions sont actuellement vides sauf pour ce qui est écrit ci-dessus
  • wordpress version 4.2.2, maçonnerie confirmée dans le dossier js
  • j’ai lu que ImagesLoaded est intégré à la maçonnerie de wordpress

Ma supposition

C’est quelque chose d’évident

Solution n°1 trouvée

La réponse

La réponse simple et embarrassante à ma propre question était que j’avais oublié d’inclure <?php wp_footer(); ?>dans le fichier footer.php.

Le lendemain cependant, j’ai découvert que ImagesLoaded n’était pas lancé à partir du pied de page comme on pouvait s’y attendre, donc cette réponse a depuis été rééditée pour montrer comment j’ai fait fonctionner correctement ImagesLoaded.

Je dois noter que Masonry s’initiait correctement à partir de la méthode des options de page html, mais les fichiers d’aide ne montrent pas comment lancer ImagesLoaded avec cette même méthode de page.

Lire également:  Wordpress : Thème personnalisé non visible dans l'apparence

Backstory (some info of possible use to others)

The next day, after adding in some test posts with thumbnails to the test blog I found that ImagesLoaded wasn’t initializing and all blocks were overlapping each other.

I then discovered that attempting to initialize even Masonry with Javascript from footer.php was not working at all either.

After another hour or two trying to figure out why neither script will initialize from either footer.php or header.php I gave up and went back to this suggestion

..why not just add it to a .js file and enqueue it with a loading
dependency on the masonry script? Then you wouldn’t have to add the
jQuery code manually to the header/footer via hooks.

Then I found again this question and answer How can I make masonry and Imagesloaded work correct. (wordpress) with an explanation how to do this.

So with thanks to those two folks I will edit this all over again and show you how I got WordPress working properly with Masonry and it’s now-built-in ImagesLoaded.


One Method On How To Add Masonry To Your WordPress Theme

Goals

  1. To have Masonry installed on your wordpress theme to make it behave
    like Pinterest.
  2. To have the page centered.
  3. To prevent the stacking on top of / overlapping of each block element.

Some Stuff To Know

  • Current WordPress versions (3.9? to 4.2.2+) come packaged with Masonry.
  • Location – wp-includes/js/masonry.min.js
  • This WordPress version of Masonry includes ImagesLoaded built-in.
  • Masonry no longer requires Jquery, though the only way I could find to get it to initialize in WordPress requires a little bit of it.

Installation and Setup


in functions.php

// to use scripts with wordpress they must first be enqueued
function enqueue_scripts() {
    wp_enqueue_script('masonry');
    wp_enqueue_script('masonryloader', get_stylesheet_directory_uri() . '/js/TaS-masonryInitializer.js', array( 'masonry', 'jquery' ) );
}
add_action('wp_enqueue_scripts','enqueue_scripts');

notes

  • because WordPress may use other scripts and plugins you install may rely on some others ‘enqueueing scripts’ is how WordPress manages them all so as not to conflict with each other. I’d go into more detail but I’m not qualified to do so.
  • you may see on some other websites examples that show you have to first register Masonry. This is not so as it is included with WordPress and so is already registered.
  • the two script we are enqueing here are first Masonry and second our little script to get masonry to initialize.
  • Jquery is also being uhh, enqueued as a dependency for the little Initializer script to work.
Lire également:  Comment supprimer le pied de page de wordpress "powered by wordpress"

in your themes folder (eg /wp-content/themes/yourThemeName/)

  1. create a folder named ‘js’

  2. inside that folder create a file named TaS-masonryInitializer.js

    • it should look like this /wp-content/themes/yourThemeName/js/TaS-masonryInitializer.js
  3. copy and paste this Javascript into that file..

    (function( $ ) {
    "use strict";
    $(function() {
        // set the container that Masonry will be inside of in a var
        // adjust to match your own wrapper/container class/id name
        var container = document.querySelector('.masonry-container');
        //create empty var msnry
        var msnry;
        // initialize Masonry after all images have loaded
        imagesLoaded( container, function() {
            msnry = new Masonry( container, {
                // adjust to match your own block wrapper/container class/id name
                itemSelector: '.block-wrapper',
                // option that allows for your website to center in the page
                isFitWidth: true
            });
        });
    });
    }(jQuery));
    

notes

  • this step is to initialize both Masonry and ImagesLoaded and to adjust the options for Masonry
  • as stated earlier, ImagesLoaded is built into the wordpress version of Masonry so no need to enqueue it separately in functions.php as you would have to do on a straight html site.
  • to measure height of each image and it’s containing block ImagesLoaded is used to prevent Masonry from loading before these heights are determined. This pause/order allows Masonry to properly calculate the height of each block. This is important if you are using height: auto; on your images, as many responsive designs do.
  • assuming your page width is responsive and set to 100%/not fixed, Masonry needs to determine how wide that 100% actually is in able to center your site on the page. The option "isFitWidth": true is how this is done. Read more about that here.
  • you can assign a column width by letting masonry choose the first block’s width and applying it as the column width or you can state explicitly the column width in the options as per this page.
  • .masonry-container is the class of the container that wraps around all your blocks that you want to behave as masonry behaves
  • it can be an ID as well if, you prefer, #masonry-container
  • it can be any name, just be sure to adjust for it in the above function
  • the above code is taken from How can I make masonry and Imagesloaded work correct. (wordpress) as well as Masonry’s own instructions
Lire également:  Wordpress : Comment déterminer si WP_DEBUG est activé ?

in index.php (or other template files depending where on your site you want masonry used)

<div class="masonry-container js-masonry">

    <div class="block-wrapper">content</div>

    <div class="block-wrapper">content</div>

    <div class="block-wrapper">content</div>

</div><!-- end masonry-container js-masonry -->

notes

  • the class « masonry-container » can be either a class or an id and can be any name you choose, just be sure to adjust for it in the TaS-masonryInitializer.js file
  • to my recollection, the class « js-masonry » is required for Masonry to find the opening div and cannot be renamed without meddling with the script itself.
  • each div classed « block-wrapper » is a different block element that you are applying the masonry alignment effect to.
  • « block-wrapper », like « masonry-container », can be any name you choose and either an id or class.

in footer.php

make certain to have included wp_footer() before your closing body tag.

<?php wp_footer(); ?>

</body>
</html>

notes

  • wp_footer is used by wordpress to enable scripts on your page in one single action. The scripts you enqueued in functions.php are hooked into wp_footer. (Excuse my terminology, I’m sure I misused a couple of words there)

in header.php

make sure you have..

<?php wp_head(); ?>

right before </head>

and as most people are probably using Masonry for a mobile friendly site these days, be sure to include the following code (again, between head and /head) to make things work on mobile browsers..

<meta name="viewport" content="width=device-width, initial-scale=1">

Veuillez me faire part de tout malentendu que j’ai et des erreurs que j’ai négligées et j’essaierai de les corriger.


Des accessoires fous à David DeSandro pour avoir écrit un très bon scénario. Consultez son site Web, il a créé d’autres trucs super cool.

Catégories : Wordpress

Jean-Michel

Jean-Michel est en charge de la partie blog du site. Il met en place la stratégie de contenu et répond aux questions fréquentes sur Wordpress.

0 commentaire

Laisser un commentaire

Avatar placeholder

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *