Another Dayu

Show Random posts in Bear Blog

Bear blog supports Embedding blog post lists, for example displaying the latest posts:

{{ posts|limit:5 }}  

However, it does not support displaying random posts. Then, I created a small plugin that replicates the official layout while showing random posts instead. The result looks like this:

First, insert the following code where you want the Random posts section to appear:

<div id="all-posts-source" style="display: none;">  
  {{ posts|limit:999 }}  
</div>  

<div id="random-post-container">  
  <p>Random posts:</p>  
  <div id="random-post-list" class="blurred">Loading...</div>  
</div>  

Then add the following script in
Settings → Header and footer directives → Footer directive.

<script>  
document.addEventListener("DOMContentLoaded", function() {  
  const sourceContainer = document.querySelector("#all-posts-source .embedded.blog-posts");  
  const targetList = document.getElementById("random-post-list");  

  if (sourceContainer && targetList) {  
    // 1. Get all original post nodes  
    const allPosts = Array.from(sourceContainer.children);  
    
    // 2. Shuffle them randomly  
    const shuffled = allPosts.sort(() => 0.5 - Math.random());  
    
    // 3. Select the first 5 posts  
    const selected = shuffled.slice(0, 5);  

    // 4. Clear the container and inject cloned nodes  
    targetList.innerHTML = '';  
    
    // Create a wrapper container consistent with the official layout  
    const wrapper = document.createElement('ul');  
    wrapper.className = 'embedded blog-posts';  
    wrapper.style.listStyle = 'none'; // Remove bullet points  
    wrapper.style.padding = '0';  

    selected.forEach(post => {  
      // cloneNode(true) preserves the full structure, including the date  
      const clone = post.cloneNode(true);  
      wrapper.appendChild(clone);  
    });  

    targetList.appendChild(wrapper);  
    targetList.classList.remove("blurred");  
    
    // Remove the hidden data source  
    document.getElementById("all-posts-source").remove();  
  }  
});  
</script>  

#bearblog #plugin