problem in adding custom page template to a template made by plugin

Im trying to make a plugin, this plugin auto generates a page template named 'page-cb.php', it also generates a prebuilt page using the wp_insert_post(). the problem is when i try to set that custom template, for the page created by wp_insert_post(), the page is created but my custom template isnt applied to it, my code is as followes:

here i make the custom template:

//Load template from specific page
add_filter( 'page_template', 'cp_page_template_loader' );

function cp_page_template_loader( $page_template ){

if ( get_page_template_slug() == 'page-cp.php' ) {
    $page_template = plugin_dir_url( __FILE__ ) . '/page-cp.php';
}
return $page_template;
}

/**
 * Add "Custom" template to page attirbute template section.
 */
add_filter( 'theme_page_templates', 'cp_page_template_maker', 10, 4 );
function cp_page_template_maker( $post_templates, $wp_theme, $post, $post_type ) {

    // Add custom template named template-custom.php to select dropdown 
    $post_templates['page-cp.php'] = __('خرید سفارشی');

    return $post_templates;
}

and this is how i make the page and pass the custom template name:

if (empty(get_page_by_title('خرید سفارشی'))) {
  $blog_id = wp_insert_post(
    array(
      'comment_status' => 'close',
      'ping_status' => 'close',
      'post_author' => 1,
      'post_title' => ucwords('خرید سفارشی'),
      'post_name' => 'cp_page',
      'post_status' => 'publish',
      'post_content' => '',
      'post_type' => 'page',
      'post_parent' => '',
      'page_template'  => 'page-cp.php',
    )
  );

}

note: the file is created in plugin root, so generally this code works when the file is in theme root and i think that should be the problem, any idea how to get this to work?

1 answer

  • answered 2021-06-19 19:18 Unbywyd

    Why do you think it doesn't work? Have you checked in the admin panel on the side? Is your template selected?

    enter image description here

    It's not enough for you to simply assign a template to the post, you need to write your own handler to intercept the display of the template , use for this page_template filter

    add_filter( 'page_template', array($this, 'set_single_template'));
    

    Complete working example:

    class customTemplate  {
        private static $instance;
    
        /**
         * The array of templates that this plugin tracks.
         */
        protected $templates;
    
        public static function get_instance() {
            if ( null == self::$instance ) {
                self::$instance = new customTemplate();
            }
            return self::$instance;
        }
    
        private function __construct() {
            $this->templates =  array(
                'page-test-blank.php' => 'Test blank page'
            );
            
            add_filter(
                'theme_page_templates', array( $this, 'add_new_template' )
            );
    
            // Changing the path for our template
            add_filter( 'page_template', array($this, 'set_single_template'));
            
            //add_action('init', array($this, 'init'));
        }
    
        // Test
        public function init() {
            wp_insert_post(
                array(
                    'comment_status' => 'close',
                    'ping_status' => 'close',
                    'post_title' => 'test page-test-blank.php',
                    'post_status' => 'publish',
                    'post_type' => 'page',
                    'page_template'  => 'page-test-blank.php',
                )
            );
        }
        
        function set_single_template( $template ) {
            $tmp = explode('/', $template);
            $tmp = explode('\\' , $tmp[count($tmp) - 1]);
            $template_file_name = $tmp[count($tmp) - 1];
    
            global $post;
            $active_template = get_post_meta($post->ID, '_wp_page_template', true);
            if($active_template != $template_file_name) {
                if(file_exists(dirname( __FILE__ ) . '/templates/'.$active_template)) {
                    return dirname( __FILE__ ) . '/templates/'.$active_template;
                }
            }
            return $template;
        }  
    
        /**
        * Adds our template to the page dropdown for v4.7+
        *
        */
        public function add_new_template( $posts_templates ) {
            $posts_templates = array_merge( $posts_templates, $this->templates );
            return $posts_templates;
        }
    
        
    }
    
    add_action( 'plugins_loaded', array( 'customTemplate', 'get_instance' ) );