如何从管理菜单更改WordPress标题图像

时间:2021-11-04 作者:pooyan golkar

我在“管理”菜单中创建了一个部分,可以上载徽标,如何用wordpress徽标(header\\u image())替换上载的图像//管理仪表板页面

<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>
//上传流程代码

<?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\'] . \'/\' . $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\'] . \'/\' . $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\' ) );

}

1 个回复
最合适的回答,由SO网友:kero 整理而成

老实说,我不完全理解为什么你需要这个自定义代码来上传图像,它应该可以与默认设置。

回答您的问题:

如果你仔细研究一下代码,就会发现

  1. header_image() 呼叫get_header_image() 并返回get_header_image() 呼叫get_theme_mod(\'header_image\', ...) 并将返回(只要不是remove-headeris_random_header_image() 退货true).
  2. get_theme_mod() 现在,最后介绍一个过滤器:theme_mod_{$name}

    add_filter(\'theme_mod_header_image\', function ($originalValue) {
        // return URL to your desired image
    });
    

相关推荐