Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonbahl/3437ffd8d0940ccb4df9b35f564d88a3 to your computer and use it in GitHub Desktop.
Save jasonbahl/3437ffd8d0940ccb4df9b35f564d88a3 to your computer and use it in GitHub Desktop.
add_action( 'init', function() {
register_graphql_connection([
'fromType' => 'Post',
'toType' => 'Category',
'fromFieldName' => 'primaryCat',
'oneToOne' => true,
'resolve' => function( \WPGraphQL\Model\Post $post, $args, $context, $info ) {
$primary_term = null;
if ( function_exists( 'the_seo_framework' ) ) {
$primary_term = the_seo_framework()->get_primary_term( $post->ID, 'category' );
}
// If there's no primary term from the SEO Framework, get the first category assigned
if ( empty( $primary_term ) ) {
$terms = get_the_terms( $post->ID, 'category' );
if ( ! empty( $terms ) ) {
$primary_term = $terms[0]->term_id;
}
}
// If there's no primary term, return null for the connection
if ( empty( $primary_term ) ) {
return null;
}
$resolver = new \WPGraphQL\Data\Connection\TermObjectConnectionResolver( $post, $args, $context, $info, 'category' );
$resolver->set_query_arg( 'include', absint( $primary_term ) );
return $resolver->one_to_one()->get_connection();
}
]);
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment