我正在构建一个能够上传自定义背景图像的主题,但现在我陷入了困境。
如何通过theme-setting.php以drupal形式正确添加FILE字段,之后如何在我的模板文件中获取该文件的公共URL?
我正在构建一个能够上传自定义背景图像的主题,但现在我陷入了困境。
如何通过theme-setting.php以drupal形式正确添加FILE字段,之后如何在我的模板文件中获取该文件的公共URL?
在您的 theme_form_system_theme_settings_alter 钩子中,您需要添加以下表单元素:
$form['theme_settings']['background_file'] = array(
'#type' => 'managed_file',
'#title' => t('Background'),
'#required' => FALSE,
'#upload_location' => file_default_scheme() . '://theme/backgrounds/',
'#default_value' => theme_get_setting('background_file'),
'#upload_validators' => array(
'file_validate_extensions' => array('gif png jpg jpeg'),
),
);
这会将文件 ID 保存到您的主题设置变量“background_file”,请注意我将上传位置设置为主题/背景,这将在您的文件夹中。
最后,您将使用 file_create_url 获得文件的完整 URL:
$fid = theme_get_setting('background_file');
$image_url = file_create_url(file_load($fid)->uri);
编辑:
在您的 template.php 中,您可以在 theme_preprocess_page 挂钩中添加变量,以便所有 tpl 都可以访问它,方法如下:
function theme_preprocess_page(&$variables, $hook) {
$fid = theme_get_setting('background_file');
$variables['background_url'] = file_create_url(file_load($fid)->uri);
}
希望这可以帮助!:D