0
votes

I have a normal posts page in an Anchor CMS theme. Beside the posts list is a category list, which I am intending to use as sorting filters for the blog posts. The category list has been output as follows, based on the Anchor Docs:

 <?php foreach(Category::dropdown() as $id => $category): ?>

     <div class="filter" data-filter=".category-<?php echo $id; ?>"><?php echo $category; ?></div>

 <?php endforeach; ?>

I then have to include a corresponding class in each article or post within that list, which would look like this:

 <?php if(has_posts()): ?>      
    <?php $i = 0; while(posts()): ?>        

        <article class="mix category-<?php echo category_id(); ?>">

    <?php endwhile; ?>
<?php endif; ?>

Notice that the article class category-[num] corresponds with the data-filter on the div "filter". This is what allows sorting.

However any way I try to do this I am getting either doubled up posts or just not working. I had tried using a foreach statement as seen in the docs:

<?php foreach(Category::dropdown() as $id => $category): ?>

     <article class="mix category-<?php echo category_id(); ?>">

<?php endforeach; ?>

but this makes posts double up, I assume because it is within a while loop?

In the database, categories and posts are in two separate tables, however the category ID is included in the posts table. I have looked for a way to echo this e.g. article_category_id but with no success so far.

How can I include the category ID in the posts list?

1

1 Answers

2
votes

Okay, found the answer to my own question.

This was a simple solution actually, once I thought about it. The various function references in Anchor CMS such as article_category etc can be defined by the user by accessing anchor > functions > articles.php.

Within this file, and based on existing functions such as

function article_category() {
    if($category = Registry::prop('article', 'category')) {
        $categories = Registry::get('all_categories');

        return $categories[$category]->title;
    }
}

I created a new function for the category ID. It looks like this:

function article_category_id() {
    if($category = Registry::prop('article', 'category')) {
        $categories = Registry::get('all_categories');

        return $categories[$category]->id;
    }
}

and then echoed this out in the posts loops:

<?php echo article_category_id(); ?>

Simple as that!