Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to filter posts by category on the home page? #1548

Open
tonybgoode opened this issue Nov 21, 2023 · 1 comment
Open

How to filter posts by category on the home page? #1548

tonybgoode opened this issue Nov 21, 2023 · 1 comment

Comments

@tonybgoode
Copy link

I want to be able to display all the posts on my home page, as it works normally, but filter out posts that are of specified categories.

I haven't figured out exactly how to modify the code to accommodate this—any tips?

I've seen there is an Unlisted feature coming in 4.0, but am hoping to come up with a solution in the meantime.

VERSION:
3.15.0

Thanks!
Tony

@ConvertedGrowth
Copy link

ConvertedGrowth commented Jan 26, 2024

Hi Tony,

While the default API doesn't offer a built-in parameter for filtering by categories (like it does for example to only show published items), you can do this with if/else statements in PHP.

For example, if you were using PHP to post a list of blogs with a link and title, you can use if/else statement to exclude particular categories. In the below example i'm blocking anything in the "General" category, but you can add more qualifiers or modify the logic to only match particular categories.

        <?php
             $pageNumber = 1;
             $numberOfItems = 5;
             $onlyPublished = true;
             $items = $pages->getList($pageNumber, $numberOfItems, $onlyPublished);
             foreach ($items as $key) {
               $page = buildPage($key);
               $relatedCategory = $page->category();
               if ($relatedCategory !== "General"){
                  echo "<a href='".$page->permalink()."'>".$page->title()."</a>";
               }
            }
        ?>

Cheers!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants