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.