Search code examples
wordpresstemplateswordpress-themingfopenfile-put-contents

Trying to create empty php file gives failed to open stream permission denied wordpress


I am trying to programmatically create a custom template file inside the active theme folder and assign it to post. I use fopen() and file_put_contents() still not able to create file.

Here is my code:

        if(isset($params["template_url"])){
            $basename = basename($params["template_url"]);
            if(!file_exists(get_stylesheet_directory()."/".$basename)){ // check if file not exist
            file_put_contents(get_stylesheet_directory()."/".$basename, unserialize($params["template_content"]));
            //$template_file = fopen(get_stylesheet_directory()."/".$basename, "a+");
            if(file_exists(get_stylesheet_directory()."/".$basename)){ // check if file created now
                //fwrite($template_file, unserialize($params["template_content"]));
                //fclose($template_file);
                update_post_meta($post_id,'_wp_page_template',$basename);
            }
            else{
                $error_message .= sprintf(__(' Error in creating template on %s.'),site_url());
            }
            } else {
                update_post_meta($post_id,'_wp_page_template',$basename);
            }
        }

Can anyone help me with this issue. I have been trying to fix it from last 1 day.

Thanks in Advance.


Solution

  • Finally I find a fix that fulfill my requirement and I am posting here in case anybody faces same situation. Rather creating file in active theme folder, I created a template file in the plugin and used below code to load the template.

    function my_page_template($page_template){
        $slug = 'slug of the page where to load my custom template';
        if ( is_page($slug) ) {
            $page_template = dirname( __FILE__ ) . '/templates/my-template.php';
        }
        return $page_template;
    }
    add_filter( 'page_template', 'my_page_template');
    

    NOTE: This code will not list the template name in the templates listing dropdown (Template) option of pages. It will load the custom template irrespective to assigned template from the admin panel of the pages.