Skip to content

Instantly share code, notes, and snippets.

@blupu blupu/add-custom-data.php
Last active Mar 10, 2018

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Aug 13, 2016

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
You can’t perform that action at this time.