Created
May 4, 2018 21:24
-
-
Save jasonbahl/d2df4874a9e3c19fd05767c21fa800a1 to your computer and use it in GitHub Desktop.
Gutenberg Page Block Template field
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
add_filter( 'graphql_page_fields', function( $fields ) { | |
$fields['blockTemplate'] = [ | |
'type' => \WPGraphQL\Types::string(), | |
'description' => __( 'The Block template defined for the page', 'oshpd-guten-blocks' ), | |
'args' => [ | |
'pageTemplate' => [ | |
'type' => \WPGraphQL\Types::string(), | |
'description' => __( 'The page template associated with the block template', 'oshpd-guten-blocks' ), | |
], | |
], | |
'resolve' => function( \WP_Post $post, array $args, $info, $context ) { | |
$page_template = ! empty( $args['pageTemplate'] ) ? $args['pageTemplate'] : get_page_template_slug( $post->ID ); | |
$saved_block_template = ! empty( $page_template ) ? get_post_meta( $post->ID, '_saved_block_template_' . $args['template'], true ) : null; | |
if ( ! empty ( $saved_block_template ) ) { | |
$template = $saved_block_template; | |
} else { | |
$template = oshpd_get_default_page_block_template( $page_template ); | |
} | |
return $template; | |
} | |
]; | |
return $fields; | |
} ); | |
/** | |
* Returns the block template associated with a particular page template | |
* | |
* @param string $page_template The slug of the page template (ex: templates/page-template.php) | |
* @return string The block template | |
*/ | |
function oshpd_get_default_page_block_template( $page_template ) { | |
$block_template = ''; | |
switch ( $page_template ) { | |
case 'templates/home.php': | |
$block_template = ' | |
<!-- wp:oshpd/homepage-hero /--> | |
<!-- wp:oshpd/latest-news /--> | |
<!-- wp:oshpd/leadership-cards /--> | |
'; | |
break; | |
case 'templates/landing-page.php': | |
$block_template = ' | |
<!-- wp:oshpd/leadership-cards /--> | |
<!-- wp:oshpd/homepage-hero /--> | |
'; | |
break; | |
} | |
$filtered_template = apply_filters( 'oshpd_get_default_page_block_template', $block_template, $page_template ); | |
return preg_replace( "/\r|\n|\t/", "", $filtered_template ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment