Skip to content

Instantly share code, notes, and snippets.

@blupu
Last active March 10, 2018 14:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blupu/27e4567aab17a800a6e306da128f9390 to your computer and use it in GitHub Desktop.
Save blupu/27e4567aab17a800a6e306da128f9390 to your computer and use it in GitHub Desktop.
WP-AppKit - Custom template if post has a specific category
<?php
/*
* @desc Add custom data to what is returned by the web services. All custom data will be available to the JS API.
* @param $post_data
* @param $post
* @param $component
*/
function wpak_add_custom_data( $post_data, $post, $component ) {
$taxonomy = 'category'; // We search for categories
$terms = get_the_terms( $post->ID, $taxonomy ); // Get the post categories
$cat_list = wp_list_pluck( $terms, 'slug' ); // Get an array of slugs only
// Add category list to post data returned by the web service
$post_data['categories'] = $cat_list;
return $post_data; // Return the modified $post_data
}
// Hook into post content web service feedback
add_filter( 'wpak_post_data', 'wpak_add_custom_data', 10, 3 );
?>
App.filter( 'template', function( template, current_screen ) {
// Detect single
if ( current_screen.screen_type === 'single' ) {
// Get post categories (added in add-custom-data.php)
var post_categories = current_screen.data.post.categories;
// Call template for specific category's slug
if ( post_categories.indexOf('any-cat-slug-here') !== -1 ){
template = 'custom-single-template'; // corresponds to custom-single-template.html
}
}
return template;
});
@muhamadrid
Copy link

I get this error on console
Uncaught TypeError: Cannot read property 'indexOf' of undefined

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment