How can I randomize the suggested blog posts underneath the current blog post using custom code in Webflow?

Published on
September 22, 2023

To randomize the suggested blog posts underneath the current blog post using custom code in Webflow, you can follow these steps:

  1. Create a Collection List:
  • In your Webflow project, navigate to the page where the blog post is displayed.
  • Add a Collection List element to the page.
  • Connect the Collection List to your blog posts Collection.
  1. Set Up the Collection List:
  • Add a Collection Item to the Collection List.
  • Design the layout of the Collection Item as per your requirements.
  • Add dynamic content elements within the Collection Item to display the title, excerpt, and other details of the suggested blog posts.
  1. Apply the Custom Code:
  • In Webflow Designer, go to the Page Settings (gear icon on the left sidebar).
  • Select the "Custom Code" tab.
  • In the "Head Code" section, add the following code:
<script>$(document).ready(function() {// Get all the Collection Items within the Collection Listvar collectionItems = $('.your-collection-list-class-name .your-collection-item-class-name');// Shuffle the Collection Items using the Fisher-Yates algorithmfunction shuffleArray(array) {  var currentIndex = array.length, temporaryValue, randomIndex;  while (0 !== currentIndex) {    randomIndex = Math.floor(Math.random() * currentIndex);    currentIndex -= 1;    temporaryValue = array[currentIndex];    array[currentIndex] = array[randomIndex];    array[randomIndex] = temporaryValue;  }  return array;}// Randomize the Collection Items and append them back to the Collection ListshuffleArray(collectionItems).appendTo('.your-collection-list-class-name');});</script>

Note:

  • Replace 'your-collection-list-class-name' with the class name of your Collection List, and 'your-collection-item-class-name' with the class name of your Collection Item.
  • Make sure you have jQuery loaded on your website. If you haven't added it yet, you can add the following line of code just before the custom code:
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha384-KyX1a4Phad6aNaFmZAV0TtdtIaJP1T8eaVRAzQvif6ZvrZ4/nHLvKnqg+ju6VI6x" crossorigin="anonymous"></script>
  1. Preview and Publish:
  • Preview your website to see the randomization in effect.
  • Publish your site for the changes to take effect on the live version.

By following these steps, the suggested blog posts underneath the current blog post in your Webflow project will be randomized using custom code.

Additional Questions:

  1. How do I add a Collection List to a page in Webflow?
  2. How can I connect a Collection List to a Collection in Webflow?
  3. What is the Fisher-Yates algorithm used for in JavaScript?