Skip to content

Instantly share code, notes, and snippets.

@themeix
Forked from izzygld/learndash-graphql.php
Created June 24, 2023 10:38
Show Gist options
  • Save themeix/f48e76b08b22c7b885827a6ee4bf74f6 to your computer and use it in GitHub Desktop.
Save themeix/f48e76b08b22c7b885827a6ee4bf74f6 to your computer and use it in GitHub Desktop.
Replace REST API with @wpgraphql with @apollographql client.
<?php
add_filter( 'register_post_type_args', function( $args, $post_type ) {
if ( 'sfwd-courses' === $post_type ) {
$args['show_in_graphql'] = true;
$args['graphql_single_name'] = 'course';
$args['graphql_plural_name'] = 'courses';
}
if ( 'sfwd-lessons' === $post_type ) {
$args['show_in_graphql'] = true;
$args['graphql_single_name'] = 'lesson';
$args['graphql_plural_name'] = 'lessons';
}
if ( 'sfwd-quiz' === $post_type ) {
$args['show_in_graphql'] = true;
$args['graphql_single_name'] = 'quiz';
$args['graphql_plural_name'] = 'quizs';
}
if ( 'sfwd-topic' === $post_type ) {
$args['show_in_graphql'] = true;
$args['graphql_single_name'] = 'topic';
$args['graphql_plural_name'] = 'topics';
}
return $args;
}, 10, 2 );
add_filter( 'register_taxonomy_args', function( $args, $taxonomy ) {
if ( 'doc_tag' === $taxonomy ) {
$args['show_in_graphql'] = true;
$args['graphql_single_name'] = 'documentTag';
$args['graphql_plural_name'] = 'documentTags';
}
return $args;
}, 10, 2 );
add_action( 'graphql_register_types', function() {
register_graphql_field( 'Courses', 'featured_media', [
'type' => 'String',
'description' => __( 'The featured_media of the course', 'learndash' ),
'resolve' => function( $post ) {
$featured_media = get_post_meta( $post->ID, 'featured_media', true );
return ! empty( $featured_media ) ? $featured_media : 'null';
}
] );
} );
add_action( 'graphql_register_types', function() {
$post_types = WPGraphQL::$allowed_post_types;
if ( ! empty( $post_types ) && is_array( $post_types ) ) {
foreach ( $post_types as $post_type ) {
$post_type_object = get_post_type_object( $post_type );
if ($post_type === 'sfwd-courses') {
register_graphql_field( $post_type_object->graphql_single_name, 'blurb', [
'type' => 'String',
'description' => __( 'The blurb of the course', 'sfwd-courses' ),
'resolve' => function( $post ) {
$blurb = get_post_meta( $post->ID, 'blurb', true );
return ! empty( $blurb ) ? $blurb : '';
}
]);
}
if ($post_type === 'sfwd-quiz') {
register_graphql_field( $post_type_object->graphql_single_name, 'total', [
'type' => 'String',
'description' => __( 'The total of the quiz', 'sfwd-quiz' ),
'resolve' => function( $post ) {
$price = get_post_meta( $post->ID, 'total', true );
return ! empty( $price ) ? $price : '';
}
]);
}
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment