Skip to content

Instantly share code, notes, and snippets.

@ToughCrab24
Last active November 21, 2024 10:02
Show Gist options
  • Select an option

  • Save ToughCrab24/1f052a70c9f9ab3c0a7502ff9382c98b to your computer and use it in GitHub Desktop.

Select an option

Save ToughCrab24/1f052a70c9f9ab3c0a7502ff9382c98b to your computer and use it in GitHub Desktop.
Adds a fieldd to smart search and adds a filter to wp graphql where input and adds a meta query to the WP Query object
<?php
add_action(
'graphql_register_types',
function() {
$types = array( 'RootQueryToPostConnectionWhereArgs', 'RootQueryToPageConnectionWhereArgs', 'RootQueryToCustomPostTypeConnectionWhereArgs' ); // Add other types as needed.
foreach ( $types as $type ) {
register_graphql_field(
$type,
'languageThisPageIs',
array(
'type' => 'String',
'description' => __( 'Filter posts by language', 'textdomain' ),
)
);
}
}
);
add_filter(
'graphql_post_object_connection_query_args',
function( $query_args, $source, $input, $context, $info ) {
if ( ! empty( $input['where']['languageThisPageIs'] ) ) {
$language_value = sanitize_text_field( $input['where']['languageThisPageIs'] );
$meta_query = array(
'relation' => 'AND',
array(
'key' => 'languageSwap.language_this_page_is', // This is the path to the ACF field which can be found on the search config page.
'value' => $language_value,
'compare' => '=',
),
);
if ( isset( $query_args['meta_query'] ) ) {
$query_args['meta_query'][] = $meta_query;
} else {
$query_args['meta_query'] = $meta_query;
}
}
return $query_args;
},
10,
5
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment