Adding Template Files - AgriLife/AgriFlex GitHub Wiki

When creating a Custom Post Type, developers will often be asked to make custom templates to display these posts. Adding these custom templates to the AgriFlex core is not allowed so you will need to conditionally include these files from your plugin directory. The code to do so is below. Be sure to properly namespace your functions.

// In this situation, template files for your custom post type will live in the root of your plugin directory.
// Ideally they would be in a subdirectory.
 
add_filter( 'archive_template', 'get_archive_template' );
function get_archive_template( $archive_template ) {
  global $post;
  $plugindir = dirname( __FILE__ );
  
  if( get_query_var( 'post_type' ) == 'your_custom_post_type' ) {
    $archive_template = $plugindir . '/custom_post_type_archive.php';
  }
  return $archive_template;
 
}
 
add_filter( 'search_template', 'get_search_template' );
function get_search_template( $search_template ) {
  global $post;
  $plugindir = dirname( __FILE__ );
  
  if( get_query_var( 'post_type' ) == 'your_custom_post_type' ) {
    $search_template = $plugindir . '/custom_post_type_archive.php';
  }
  return $search_template;
 
}
 
add_filter( 'single_template', 'get_single_template' );
function get_single_template( $single_template ) {
  global $post;
  $plugindir = dirname( __FILE__ );
  
  if( get_query_var( 'post_type' ) == 'your_custom_post_type' ) {
    $single_template = $plugindir . '/custom_post_type_single.php';
  }
  return $single_template;
 
}