Change WordPress header image from admin menu

Question

I want to change the logo of the site that is inside the theme customization, from admin menu. I want the customization change when I change logo from admin menu. I put the photo upload section in the admin panel. And I want the logo photo to be uploaded from admin panel.
//admin dashboard page

<img alt="" src="<?php header_image() ?>">
        <form action="<?php echo get_stylesheet_directory_uri() ?>/process_upload.php" method="post" enctype="multipart/form-data">
            Your Logo: <input type="file" name="profilepicture" size="25" />
            <input type="submit" name="submit" value="Submit" />
        </form>

//upload process code

<?php
require( dirname(__FILE__) . '/../../../wp-load.php' );
$theme_root = get_theme_root();
$wordpress_upload_dir = wp_upload_dir();
$i = 1; 

$profilepicture = $_FILES['profilepicture'];
$new_file_path = $wordpress_upload_dir['path'] . "https://wordpress.stackexchange.com/" . $profilepicture['name'];
$new_file_mime = mime_content_type( $profilepicture['tmp_name'] );

if( empty( $profilepicture ) )
    die( 'File is not selected.' );

if( $profilepicture['error'] )
    die( $profilepicture['error'] );
    
if( $profilepicture['size'] > wp_max_upload_size() )
    die( 'It is too large than expected.' );
    
if( !in_array( $new_file_mime, get_allowed_mime_types() ) )
    die( 'WordPress doesn't allow this type of uploads.' );
    
while( file_exists( $new_file_path ) ) {
    $i++;
    $new_file_path = $wordpress_upload_dir['path'] . "https://wordpress.stackexchange.com/" . $i . '_' . $profilepicture['name'];
}

// looks like everything is OK
if( move_uploaded_file( $profilepicture['tmp_name'], $new_file_path ) ) {
    

    $upload_id = wp_insert_attachment( array(
        'guid'           => $new_file_path, 
        'post_mime_type' => $new_file_mime,
        'post_title'     => preg_replace( '/.[^.]+$/', '', $profilepicture['name'] ),
        'post_content'   => '',
        'post_status'    => 'inherit'
    ), $new_file_path );

    // wp_generate_attachment_metadata() won't work if you do not include this file
    require_once( ABSPATH . 'wp-admin/includes/image.php' );

    // Generate and save the attachment metas into the database
    wp_update_attachment_metadata( $upload_id, wp_generate_attachment_metadata( $upload_id, $new_file_path ) );

    // Show the uploaded file 'in browser
    wp_redirect( admin_url( '/admin.php?page=coalition-setting' ) );

}

0
pooyan golkar 1 year 2021-11-04T07:39:01-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse