Skip Navigation

[Resolved] Custom archive query v2

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
- 10:00 – 13:00 10:00 – 13:00 10:00 – 13:00 10:00 – 13:00 10:00 – 13:00 -
- 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 -

Supporter timezone: Asia/Kolkata (GMT+05:30)

This topic contains 1 reply, has 2 voices.

Last updated by Minesh 1 year, 3 months ago.

Assisted by: Minesh.

Author
Posts
#2652259

Waqar assisted me with a prior support question: https://toolset.com/forums/topic/custom-archive-query/. This is an extension of that question.

I now need to filter a CPT archive query by a custom field of the CPT. In this case, I have a "Business" CPT which has a "Membership Status" custom field. I want to filter the "Business" archive query to only include those businesses with the "Membership Status" field set to "Approved".

My attempt at modifying the archive query is resulting in a fatal error:

function archive_business_active_member_only( $query ) {
if ( ! is_admin() && $query->is_main_query() ) {
/* Not an admin page query but a query for the front-end of site */
/* Check for archive query of Business post-type */
if ( is_post_type_archive( 'business' ) ) {
/* Get all users with role of "Active Member" */
$user_ids = get_users( [
'role' => 'member_active',
'fields' => 'ID'
] );

/* Only include posts whose authors have the "Active Member" role */
$query->set( 'author__in', $user_ids );

/* Only include Businesses whose "Membership Status" is set to "Approved" */
$query->set = ( 'meta_key', 'membership-status' );
$query->set = ( 'meta_value', 'approved' );
$query->set = ( 'meta_compare', '=' );

/* Set the orderby to "title" and order to "ASC" to sort Business archive by ascending title */
$query->set( 'order', 'ASC' );
$query->set( 'orderby', 'title' );
}
}
}
add_action( 'pre_get_posts', 'archive_business_active_member_only' );

Any help identifying the issue is appreciated...

Thanks!

#2652375

Minesh
Supporter

Languages: English (English )

Timezone: Asia/Kolkata (GMT+05:30)

Hello. Thank you for contacting the Toolset support.

Can you please try to use the following code to set the meta query and try to resolve your issue.

Toolset custom field saved with 'wpcf-' prefix so you will have to use the custom field key (name) as: wpcf-membership-status

/* Only include Businesses whose "Membership Status" is set to "Approved" */
$meta_query = array(
            array(
                'key'       => 'wpcf-membership-status',
                'value'     =>'approved',
                'compare'   => '='
            )
        );
 
        $query->set( 'meta_query', $meta_query );