在 WordPress 中使用 Options Framework 创建一个自定义相册功能,可以通过以下步骤实现:
- 集成 Options Framework
首先,确保你已经在你的主题中集成了 Options Framework。如果尚未集成,可以按照以下步骤操作:
下载 Options Framework。
将 options.php 文件和 inc/ 文件夹复制到你的主题根目录中。
在主题的 functions.php 文件中添加以下代码:
define('OPTIONS_FRAMEWORK_DIRECTORY', get_template_directory_uri() . '/inc/');
require_once dirname(__FILE__) . '/inc/options-framework.php';
- 创建自定义相册选项
在 options.php 文件中,定义一个自定义选项用于上传图片。可以使用 upload 类型的字段来实现:
$options[] = array(
'name' => __('相册图片', 'theme_textdomain'),
'desc' => __('上传相册图片', 'theme_textdomain'),
'id' => 'gallery_images',
'type' => 'upload',
'std' => '',
'class' => 'gallery',
'multiple' => true // 允许上传多张图片
);
- 添加 JavaScript 以支持多图片上传
Options Framework 默认支持单图片上传,但需要额外的 JavaScript 代码来支持多图片上传。在主题的 functions.php 文件中添加以下代码:
function my_theme_custom_scripts() {
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('.gallery-upload-button').click(function() {
var uploadButton = $(this);
var customUploader = wp.media({
title: '<?php _e("选择图片", "theme_textdomain"); ?>',
button: {
text: '<?php _e("选择图片", "theme_textdomain"); ?>'
},
multiple: true // 允许选择多张图片
}).on('select', function() {
var attachments = customUploader.state().get('selection').toJSON();
var galleryContainer = uploadButton.prev('.gallery-container');
galleryContainer.empty();
$.each(attachments, function(index, attachment) {
galleryContainer.append('<div class="gallery-item"><img src="' + attachment.url + '" alt="' + attachment.title + '"/><input type="hidden" name="gallery_images[]" value="' + attachment.id + '"/></div>');
});
}).open();
});
});
</script>
<?php
}
add_action('admin_enqueue_scripts', 'my_theme_custom_scripts');
- 修改 Options Framework 的 HTML 结构
在 options.php 文件中,为相册图片字段添加自定义的 HTML 结构:
function my_theme_render_gallery_field($args) {
$options = get_option('of_options');
?>
<div class="gallery-container">
<?php
if (!empty($options[$args['id']])) {
foreach ($options[$args['id']] as $image_id) {
echo '<div class="gallery-item">' . wp_get_attachment_image($image_id, 'thumbnail') . '<input type="hidden" name="' . $args['id'] . '[]" value="' . $image_id . '"/></div>';
}
}
?>
</div>
<input type="button" class="button gallery-upload-button" value="<?php _e('添加图片', 'theme_textdomain'); ?>" />
<?php
}
- 保存和显示相册
在主题的适当位置(如 header.php 或 footer.php),使用保存的图片 ID 来显示相册:
$gallery_images = get_option('gallery_images');
if ($gallery_images) {
echo '<div class="custom-gallery">';
foreach ($gallery_images as $image_id) {
echo '<img src="' . wp_get_attachment_url($image_id) . '" alt="' . get_post_field('post_title', $image_id) . '">';
}
echo '</div>';
}
- 样式调整
根据需要在主题的 style.css 文件中添加样式,以美化相册的显示效果。
原文