How to show a list of random posts

Hello everyone!
i have a widget that shows the latest posts on my blog, i want to change that and make it show random posts every time the page refreshes if that possible
this is the code of the widget which shows the latest posts

{{- $recent := where .Site.RegularPages "Section" "in" .Site.Params.mainSections }}
{{- $recent_num := (.Site.Params.widgets.recent_num | default 10) }}

{{- if $recent }}
<div class="widget-recent widget">
	<h4 class="widget__title">{{ T "recent_title" }}</h4>
	<div class="widget__content">
		<ul class="widget__list">
			{{- range first $recent_num $recent }}
			<li class="widget__item">
				<a class="widget__link widget-recent__item" href="{{ .RelPermalink }}">
				{{- if .Params.thumbnail }}
					<img class="widget-recent__thumbnail" src="{{ .Params.thumbnail }}"/>
					{{ .Title }}
				{{- else }}
					- {{ .Title }}
				{{- end }}
				</a>
			</li>
			{{- end }}
		</ul>
	</div>
</div>
{{- end }}

Do want to show random pages every time you build the site, or every time someone visits the site?

random posts every time someone visit the blog

As Hugo is a static site generator, you’ll need to handle that with JavaScript.

Perhaps your list page contains summaries of all of your posts, each within a <div id="n" class="summary">, where n is a sequential number ranging from 1 to the number of posts. Set the CSS for div.summary to display: none initially.

Then have JavaScript generate a list of 5 random numbers between 1 and the number of posts. Then iterate through the list, setting the style for div#n.summary to display: block.

1 Like

thank you for trying to help, iam a newbie i thought this gonna be easy and i can do this just by changing a line on the code above

i tried with this Show 5 random posts? but it didn’t work

You can use that kind of approach to randomize posts at time of build, but not to randomize with each user’s visit to a site.

i found the solution for this here How to use shuffle on my partiall

See my previous comment.

1 Like