最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

wp query - Randomizing Wordpress Custom Post Type Sorting Through Them Without Page Refresh

programmeradmin7浏览0评论

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>
发布评论

评论列表(0)

  1. 暂无评论