Create a custom archive page for a custom post type in a plugin

What you need is hooking template_include filter and selectively load your template inside plugin.

As a good practice, if you plan to distribute your plugin, you should check if archive-my_plugin_lesson.php (or maybe myplugin/archive-lesson.php) exists in theme, if not use the plugin version.

In this way is easy for users replace the template via theme (or child theme) without edit the plugin code.

This is the method used by popular plugins, e.g. WooCommmerce, just to say one name.

add_filter('template_include', 'lessons_template');

function lessons_template( $template ) {
  if ( is_post_type_archive('my_plugin_lesson') ) {
    $theme_files = array('archive-my_plugin_lesson.php', 'myplugin/archive-lesson.php');
    $exists_in_theme = locate_template($theme_files, false);
    if ( $exists_in_theme != '' ) {
      return $exists_in_theme;
    } else {
      return plugin_dir_path(__FILE__) . 'archive-lesson.php';
    }
  }
  return $template;
}

More info on Codex for

Leave a Comment