Display Kentico Content Based on a Certain Tag Passed Through a Query String

Display Kentico Content Based on a Certain Tag Passed Through a Query String

Displaying content based on a certain tag passed through a query string involves retrieving the tag value from the query string parameter and using it to filter and display the relevant content.

Below is an example demonstrating how you might achieve this:

Assuming you have a page URL like: https://yoursite.com/tagged-content?tag=yourtagname

You can retrieve the tag value from the query string and use it to filter the content on your page:

using CMS.DocumentEngine;
using CMS.SiteProvider;
using System;

public partial class TaggedContentPage : CMSPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Check if the 'tag' parameter exists in the query string
        if (!String.IsNullOrEmpty(Request.QueryString["tag"]))
        {
            // Retrieve the tag value from the query string
            string tagValue = Request.QueryString["tag"];

            // Get the current site ID
            int siteId = SiteContext.CurrentSiteID;

            // Retrieve documents tagged with the specified tag
            var documents = DocumentHelper.GetDocuments()
                .Published()
                .OnSite(siteId)
                .Culture(SiteContext.CurrentCulture.CultureCode)
                .WhereContains("DocumentTags", ";" + tagValue + ";") // Check if the tag is contained in DocumentTags field
                .OrderBy("DocumentPublishFrom desc") // Optionally, order the results
                .TypedResult;

            // Now you have the documents tagged with the specified tag
            // You can loop through the 'documents' collection and display them as needed
            foreach (var document in documents)
            {
                // Access document properties like document.DocumentName, document.DocumentUrl, etc.
                // Display or process the content as required
            }
        }
        else
        {
            // Handle the case when the 'tag' parameter is not present in the query string
            // Redirect or display a message indicating that no tag was provided
        }
    }
}

The code checks if the ‘tag‘ parameter exists in the query string.

If the tag parameter is present, it retrieves the tag value.

Then, it uses the Kentico API (DocumentHelper.GetDocuments()) to fetch documents tagged with the specified tag.

You can modify the code inside the foreach loop to display or process the content as needed based on the retrieved documents.

Make sure to handle exceptions and perform necessary error checking based on your specific requirements.

Additionally, consider implementing proper error handling or redirecting users if the ‘tag‘ parameter is missing or invalid in the query string.