I have a custom category page which displays child categories of the current category instead of posts. I would like to filter the child categories based on a custom field so only selected categories are displayed.
The custom field is a single check box which I added to category pages using the Advanced Custom Fields Plugin.

This is the code I’m using to get the child categories:

$cat = get_category( get_query_var( 'cat' ) );
$cat_id = $cat->cat_ID;

$child_categories = get_categories(
    array(
        'parent'     => $cat_id,
        'orderby'    => 'id',
        'order'      => 'DESC',
        'hide_empty' => '0'
    )
);

I’m now using meta_query as suggested by @birgire but it’s still not working. I changed the custom field from a check box to “true/false”. This is the code I’m currently using:

$cat = get_category( get_query_var( 'cat' ) );
$cat_id = $cat->cat_ID;

$child_categories = get_categories(
    array(
        'parent'     => $cat_id,
        'orderby'    => 'id',
        'order'      => 'DESC',
        'hide_empty' => '0',
        'meta_query' => array(
            array(
                'key'     => 'show_cat',
                'value'   => 'true',
                'compare' => '=',
            )
        )
    )
);

1 Answer
1

You should be able to use the meta_query attribute that uses WP_Meta_Query behind the scenes:

$child_categories = get_categories(
    array(
        'parent'     => $cat_id,
        'orderby'    => 'id',
        'order'      => 'DESC',
        'hide_empty' => '0',
        'meta_query' => array(
            array(
                'key'     => 'mykey',     // Adjust to your needs!
                'value'   => 'myvalue',   // Adjust to your needs!
                'compare' => '=',         // Default
            )
        )
    )
);

This assumes the term meta data to be stored in the term meta table, e.g. added with add_term_meta() or update_term_meta(), as of WordPress 4.4.

The previous approach was to store the term meta data in the options table, as seems to be the case with the ACF plugin OP is using.

Leave a Reply

Your email address will not be published. Required fields are marked *