I am creating directory and a css file using conventional php method. Here it is

$upload_dir = wp_upload_dir();
$dirpath = $upload_dir['basedir'] . '/dynamic/';
$filepath = $dirpath. 'dynamic.css';

if( !file_exists($filepath) ){
  $fh = fopen($filepath, "w");

But I want to use native wp filesystem .I have tried

if(!$wp_filesystem->is_dir( $dirpath) 
   $wp_filesystem->mkdir( $dirpath);

Now How can I create the file dynamic.css?


This is pretty tough for me to through this. But You may follow this .

1.First let us check for the folder if it exists we will not execute anymore.

    if ( file_exists(trailingslashit(WP_PLUGIN_DIR).'demo' ) ) {

2.Now we will get the credential

    if (false === ($creds = request_filesystem_credentials($url, $method, false,    false, $form_fields) ) ) {
    return true;

3.If we do not have file write permission ask for it

    if ( ! WP_Filesystem($creds) ) {
    // our credentials were no good, ask the user for them again
    request_filesystem_credentials($url, $method, true, false, $form_fields);
    return true;

4.Everythig is good now let us create directory

    global $wp_filesystem;
    $plugdir = $wp_filesystem->wp_plugins_dir() .'demo';

5.Now we will create php vars or include file

    $header = <<<END
   Your data variable. You can use include or require for separate file

6.Our last part

    $plugfile = trailingslashit($plugdir).'style'.'.css';

if ( ! $wp_filesystem->put_contents( $plugfile, $header, FS_CHMOD_FILE) ) {
    echo 'Failed';
    return true;

You can wrap the whole block in a function and execute it with suitable hooks. Hope it helps

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.