From f76c715cdabfc6b539238d3e802bb66457328ffc Mon Sep 17 00:00:00 2001 From: Jacob Arriola Date: Mon, 30 Mar 2020 13:44:39 -0700 Subject: [PATCH] =?UTF-8?q?=F0=9F=A7=98=F0=9F=8F=BC=E2=80=8D=E2=99=82?= =?UTF-8?q?=EF=B8=8F=20Initial=20commit?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 0 README.md | 9 ++++++ yoast.php | 80 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 89 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 yoast.php diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e69de29 diff --git a/README.md b/README.md new file mode 100644 index 0000000..88b17b8 --- /dev/null +++ b/README.md @@ -0,0 +1,9 @@ +# Registering Types and Fields: Pair Programming with Jacob Arriola & Jason Bahl + +This is the reference repo used during a pair programming session with Jacob Arriola and Jason + Bahl. The essence of this session was to learn how to extend the WPGraphQL plugin's schema. + + ## References + * [Jason Bahl Twitter](https://twitter.com/jasonbahl/) + * [WPGraphQL](https://docs.wpgraphql.com/) + * [YouTube of session](https://www.wpgraphql.com/2020/03/30/registering-types-and-fields-pair-programming-with-jacob-arriola/) \ No newline at end of file diff --git a/yoast.php b/yoast.php new file mode 100644 index 0000000..4ef31e0 --- /dev/null +++ b/yoast.php @@ -0,0 +1,80 @@ + 'SEO data for a given post', + 'fields' => [ + 'title' => [ + 'type' => 'String', + 'description' => 'The SEO title for the post', + 'resolve' => function ( $source, $args, $info, $context ) { + + /* @var $yoast \WPSEO_Frontend */ + /* @var $post \WPGraphQL\Model\Post */ + + + $yoast = $source['yoast']; + $post = $source['post']; + + $title = $yoast->get_seo_title( $post ); + + // Provide a fallback if yoast title wasn't set + if ( empty( $title ) ) { + // Go get the Yoast formatted title + $site_title_format = $yoast->get_title_from_options( 'title-' . $post->post_type, $post ); + + $title = sprintf( '%s %s', $post->titleRaw, $site_title_format ); + } + + $yoast->reset(); + + return $title; + }, + ], + 'description' => [ + 'type' => 'String', + 'description' => 'The SEO meta description for the post', + 'resolve' => function ( $source, $args, $info, $context ) { + $meta = get_post_meta( $source['post']->ID, '_yoast_wpseo_metadesc', true ); + + return ! empty( $meta ) ? $meta : null; + }, + ], + ], + ] ); + + + $allowed_post_types = get_post_types( [ 'show_in_graphql' => true ], 'objects' ); + + if ( ! empty( $allowed_post_types ) ) { + + foreach ( $allowed_post_types as $allowed_post_type ) { + + register_graphql_field( $allowed_post_type->graphql_single_name, 'seo', [ + 'type' => SEO_TYPE, + 'resolve' => function ( $post, $args, $info, $context ) { + $yoast = \WPSEO_Frontend::get_instance(); + + return [ 'post' => $post, 'yoast' => $yoast ]; + }, + ] ); + } + } + + +} ); + + + + + + + + + +