lab.elastik

man - Bloc 3

Derniers cours : man

Les cours sont classés par ordre où ils ont été donnés, du plus récent au plus ancien.

Launch Youtube video when video enters viewport

man

How to launch an emnedded Youtube video when it enters the viewport: This can be achieved by leveraging the Intersection Observer API, which allows you to configure a callback function that executes when an observed element enters or exits the viewport.

Important Notes:

    • The YouTube iframe API requires that you append ?enablejsapi=1 to the URL to enable control of the iframe via postMessage.
    • The postMessage method is used to send commands to the YouTube video player, such as playVideo and pauseVideo.

For a single video

				
					<!-- for 1 video -->

<iframe id="youtubeVideo" width="560" height="315" 
        src="https://www.youtube.com/embed/EDkABFzGTGg?enablejsapi=1&mute=1" 
        title="YouTube video player" frameborder="0" 
        allow="accelerometer; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" 
        referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>

<script>
document.addEventListener("DOMContentLoaded", function() {
    var video = document.getElementById('youtubeVideo');
    var options = {
        root: null, // observing relative to viewport
        rootMargin: '0px',
        threshold: 0.5 // trigger when at least 50% of the video is visible
    };

    function handleIntersect(entries, observer) {
        entries.forEach(function(entry) {
            if (entry.isIntersecting) {
                // Video enters the viewport - play the video
                video.contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', 'https://www.youtube.com');
            } else {
                // Video exits the viewport - pause the video
                video.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', 'https://www.youtube.com');
            }
        });
    }

    var observer = new IntersectionObserver(handleIntersect, options);
    observer.observe(video);
});
</script>

				
			

For multiple videos

				
					<!-- for several videos  -->

<iframe id="youtubeVideo1" width="560" height="315" 
        src="https://www.youtube.com/embed/EDkABFzGTGg?enablejsapi=1&mute=1" 
        title="YouTube video player" frameborder="0" 
        allow="accelerometer; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" 
        referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
        
<hr style="margin-bottom:50vh">

<iframe id="youtubeVideo2" width="560" height="315" 
        src="https://www.youtube.com/embed/_AOA6M9Ta2I?enablejsapi=1&mute=1" 
        title="YouTube video player" frameborder="0" 
        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" 
        referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>

<script>
document.addEventListener("DOMContentLoaded", function() {
    var videos = document.querySelectorAll('iframe[id^="youtubeVideo"]'); // Selects iframes with IDs starting with 'youtubeVideo'
    var options = {
        root: null, // observing relative to viewport
        rootMargin: '0px',
        threshold: 0.5 // trigger when at least 50% of the video is visible
    };

    function handleIntersect(entries, observer) {
        entries.forEach(function(entry) {
            if (entry.isIntersecting) {
                // Video enters the viewport - play the video
                entry.target.contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', 'https://www.youtube.com');
            } else {
                // Video exits the viewport - pause the video
                entry.target.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', 'https://www.youtube.com');
            }
        });
    }

    var observer = new IntersectionObserver(handleIntersect, options);
    videos.forEach(function(video) {
        observer.observe(video); // Observe each video
    });
});
</script>

				
			

Comment inclure les données des Champs Personnalisés Avancés (Advanced Custom Fields) dans la recherche WordPress

man

WordPress ne recherche pas dans les champs personnalisés !

Bien qu’ACF fasse un excellent travail en utilisant les champs personnalisés de WordPress (post meta) pour le stockage de données structurées, WordPress ne recherche aucun de ces contenus !

De nombreux sites construits par WordPress qui utilisent ACF placent la grande majorité du contenu dans des champs personnalisés (et non dans l’éditeur principal) et ce, pour de bonnes raisons, cela offre une interface beaucoup plus agréable à utiliser et réduit les erreurs.

Malheureusement, un effet secondaire de cela signifie que presque aucun contenu de votre site n’est pris en compte lors de l’exécution des recherches. C’est un énorme problème !

Pour résoudre cela, nous devons modifier la requête de recherche de WordPress pour inclure les champs personnalisés.

				
					<?php
//https://curious-human-b.medium.com/how-to-include-advanced-custom-fields-data-into-wordpress-search-77247f0aa23e
/**  
* Join posts and postmeta tables  
*  
* http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_join  */ 
function customfields_search_join( $join ) {     
   global $wpdb;      
   if ( is_search() ) {             
      $join .=' LEFT JOIN '.$wpdb->postmeta. ' ON '. $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id ';     
   }      
  return $join; 
} 
add_filter('posts_join', 'customfields_search_join' );

function customfields_search_where( $where) {
   global $pagenow, $wpdb;
   
   if( is_search() ) {
      $where = preg_replace(
"/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/","(".$wpdb->posts.".post_title LIKE $1) OR 
(".$wpdb->postmeta.".meta_value LIKE $1)", $where );
     
    }
    
    return $where;
}
add_filter('posts_where', 'customfields_search_where' );

function customfields_search_distinct( $where ) {     
      global $wpdb;
      if ( is_search() ) {
         return "DISTINCT";
     }
  return $where;
} 
add_filter( 'posts_distinct', 'customfields_search_distinct' );

?>

				
			
				
					// rechercher aussi parmi les taxonomies

function customfields_taxonomies_search_join( $join ) {
    global $wpdb;
    if ( is_search() ) {
        // Join to the term_relationships table to access term_taxonomy_id
        $join .= " LEFT JOIN {$wpdb->term_relationships} ON ({$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id) ";
        
        // Join to the term_taxonomy table to ensure we can filter by taxonomy
        $join .= " LEFT JOIN {$wpdb->term_taxonomy} ON ({$wpdb->term_relationships}.term_taxonomy_id = {$wpdb->term_taxonomy}.term_taxonomy_id) ";
        
        // Join to the terms table to access the name of the term
        $join .= " LEFT JOIN {$wpdb->terms} ON ({$wpdb->term_taxonomy}.term_id = {$wpdb->terms}.term_id) ";
    }
    return $join;
}
add_filter('posts_join', 'customfields_taxonomies_search_join');

function customfields_taxonomies_search_where( $where ) {
    global $wpdb;
    
    if ( is_search() ) {
        $where .= " OR ({$wpdb->terms}.name LIKE '%".get_search_query()."%' AND {$wpdb->term_taxonomy}.taxonomy IN ('your_custom_taxonomy_here', 'another_taxonomy'))";
    }
    
    return $where;
}
add_filter('posts_where', 'customfields_taxonomies_search_where');

// You might still want to use your customfields_search_distinct function to avoid duplicate results:
// add_filter('posts_distinct', 'customfields_search_distinct');

				
			

man

Une amie graphiste peinait à créer une grille de boucle dont les articles devaient être illustrés par un hexagone. Avec beaucoup de café un peu d'aide d'une IA j'ai réussi à faire ceci.