• Hey there!
    just wanted to know if there is a way to group posts by their custom fields?
    let’s say something like this:
    I have a <select> Custom field named “food name” ->
    I want to display a frontend page that will display two columns: “vegetables” & “fruits”.
    so if you select “apple” or “banana” on the post custom field – it need to be injected to the “fruits” column – but if you choose “cucumber” or “broccoli” it will be injected to the “vegetables” column.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Hi,
    Would it be better to create a “Food Category” taxonomy, and have “Fruits” and “Vegetables” be two of the terms in there?

    It can be easier and more efficient to do this sort of thing by taxonomy rather than custom field.

    That said, you can get the value of your custom field and then tell your template to do something as a result (like putting things in certain columns.)
    See:
    https://codex.www.ads-software.com/Function_Reference/get_post_meta

    Good luck,
    Paul

    Moderator bcworkz

    (@bcworkz)

    You can alter the query so the posts are sorted by post_meta, but it would be alphabetical. Apples will appear before broccoli, but grapes will appear after broccoli. You do not appear to have any mechanism to know if a value entered is a fruit or vegetable.

    This is where a taxonomy works well, any new term can have a parent selected of either fruit or vegetable. Now your code can know which column a post belongs by the term’s parent. Having the query sort by taxonomy parents is beyond the default syntax, but query filters exist so you can create very complex custom queries.

    Instead of having the query sort the posts, you could have PHP do the sorting within the loop itself. Or you could do a hybrid, use PHP to run two queries, one for all fruits, then again for all vegetables. There’s likely several other viable approaches to this.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘FrontEnd Grouping by Custom Fields’ is closed to new replies.