I have content on my site that can't be shown in some countries and requires a basic level of geo-targeting, based on the users profile and not by any form of IP geo-targeting.
I have set up an address field on the users profile with country and created a matrix block with a geo-targeting toggle (lightswitch field) for my entries. Then I'm using the below code to:
- Show all entries to logged out users (as we do not know their country at this point)
Only show content with no geo-targeting or where the users country matches a country code of geo-targeted content.
{% set category = craft.categories() .all() %}
{% set params = { section: 'articlesWhitepapers', typeId: 'not 7', relatedTo: category } %}
{% set user = user is defined ? user : currentUser %}
{% set recentPosts = craft.entries(params)
.with([ ['companyName.companyLogo', { kind: 'image' }, { withTransforms: ['featuredImage'] }], 'companyName',['author.userPicture', { kind: 'image' }, { withTransforms: ['featuredImage'] }]])
.orderBy('RAND()')
.limit(2)
.all()
%}
{# Fetch the entries #}
{% set entries = recentPosts %}
{% for entry in entries %}
{% set relatedCompany = entry.companyName? entry.companyName[0] : null %}
{% if craft.app.user.isGuest %}
{# Show Everything Regardless #}
{% include "home/_main-feat" %}
{% else %}
{# Check Geo Targeting #}
{% for block in entry.addArticlePaper %}
{# get the matrix block by type #}
{% if block.type == "addArticleOrPaper" %}
{% if block.geoTargetContent %}
{% for country in block.orAddCustomGeoTargeting %}
{% set country = country.value %}
{# use the variable to filter the entries #}
{% if country == user.location.countryCode %}
{% include "home/_main-feat" %}
{% endif %}
{% endfor %}
{% else %}
{% include "home/_main-feat" %}
{% endif %}
{% endif %}
{% endfor %}
{% endif %}
{% endfor %}
This is working great and the correct content is displayed. The problem is I always want to show two pieces of content and currently it is checking the limited results and returning either 0, 1 or 2 pieces of content as its using the if logic against only two results. How would I restructure the above to continue to allow my geo-targeting to work correctly whilst ensuring there are always two pieces of content shown? I have tried a few different ways but no luck so far!
many thanks in advance!!