TransWikia.com

Randomizing Wordpress Custom Post Type Sorting Through Them Without Page Refresh

WordPress Development Asked on December 6, 2021

So in essence, we have a custom post type to create quotes – we can pull them up and randomize on page refresh normally, however when it comes to getting them to refresh to a new random quote, every say, 10 seconds, it doesn’t seem to want to work.

The solution we came up with was to make the WP_Query, pull the whole list of quotes, then convert them to json for javascript to handle the randomizing without refresh, but javascript isn’t my strong suite and it’s tripping up the process.

The other part I haven’t quite figured out is how to pass an ACF field into json for javascript to parse.

Here is the code:

<?php
    remove_all_filters( 'posts_orderby' );
    $args = array(
        'post_type'         => 'quotes',
        'posts_per_page'    => -1
    );
    $quote_pull = new WP_Query( $args );
?>
<script type="text/javascript">
    var post_info = <?php echo json_encode( $quote_pull->posts ); ?>;
</script>
<script type="text/javascript" src="<?=get_template_directory_uri();?>/assets/js/quotes.js"></script>
<div class="mySlides">
    <p class="is-size-4 is-italic has-text-left" id="quoteShowText"></p>
    <p class="is-size-4 has-text-right" id="quoteShowName">-</p>
</div>
<?php
wp_reset_query(); ?>
<script>
    (function() {
        console.log('Loaded');
    });
    getQuote();
</script>

And finally, the JS:

<script>
    function quoteRandomizer(){
        var randomNumber = Math.floor(Math.random() * (post_info.length));
        var quoteText = post_info[randomNumber].the_quote;
        var quoteName = post_info[randomNumber].post_title;
        document.getElementById('quoteShowText').innerHTML = quoteText;
        document.getElementById('quoteShowName').innerHTML = '-' + quoteName;
        const text = document.querySelector(".quoteEffect");
        const strText = text.textContent;
        const splitText = strText.split("")
        text.textContent = "";
        for(let i = 0; i < splitText.length; i++) {
            text.innerHTML += "<span>" + splitText[i] + "</span>";
        }
    }
    function getQuote(){
        quoteRandomizer();
        setInterval(() => {
            quoteRandomizer()
        }, 1000);
    }
</script>

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP