3

I coded a wordpress plugin using php's 'copy()' to copy a file from my plugin directory to my theme directory, but it's not working:

<?
function file_replace() {

    $plugin_dir = plugin_dir_path( __FILE__ ) . '/library/front-page.php';
    $theme_dir = get_stylesheet_directory() . 'front-page.php';
    copy($plugin_dir, $theme_dir);

    if (!copy($plugin_dir, $theme_dir)) {
    echo "failed to copy $plugin_dir to $theme_dir...\n";
    }
}

add_action( 'wp_head', 'file_replace' );

I thought maybe I should use ! $wp_filesystem->put_contents() but I'm not exactly sure how to do that or if that would even be the right way to go. Any ideas on the best way to copy a file from a plugin to a theme directory?

Thanks

3

To answer your question, you have specified the paths incorrectly: plugin_dir_path( __FILE__ ) already has a trailing slash at the end (having two trailing slashes should not be a problem, but safer is to have one) and get_stylesheet_directory() comes with no trailing slash at the end, so you have to add one before adding the filename. Your final code should be like this:

<?php
function file_replace() {

    $plugin_dir = plugin_dir_path( __FILE__ ) . 'library/front-page.php';
    $theme_dir = get_stylesheet_directory() . '/front-page.php';

    if (!copy($plugin_dir, $theme_dir)) {
        echo "failed to copy $plugin_dir to $theme_dir...\n";
    }
}

add_action( 'wp_head', 'file_replace' );

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.