✨ Professional WordPress development, custom website builder, efficient on-line, cooperate and enjoy optimization services! 🚀
记录一下最近项目里折腾的功能:不用WooCommerce,而是通过自定义分类来管理产品,并想给它加上多图相册功能。
下面的代码可以实现:在后台编辑产品分类时,页面底部会出现一个相册上传框。图片上传后,可以用Elementor的模块在前端展示。
但实际用下来发现,前端图片偶尔会不显示,不太稳定。所以最后还是用了ACF,一步到位,省心很多。
这段代码就当是留个底,供有兴趣的朋友研究玩玩,正式项目可别用。
function add_gallery_meta_box() {
    add_meta_box(
        'article_gallery',
        '图片相册',
        'render_gallery_meta_box',
        'post',
        'normal',
        'high'
    );
}
add_action('add_meta_boxes', 'add_gallery_meta_box');
function render_gallery_meta_box($post) {
    $images = get_post_meta($post->ID, '_article_gallery', true);
    echo '<input type="hidden" name="article_gallery_nonce" value="' . wp_create_nonce('article_gallery_nonce') . '">';
    echo '<button type="button" id="upload_images_button">上传图片</button>';
    echo '<div id="gallery_preview">';
    if ($images) {
        foreach ($images as $img_id) {
            $img_url = wp_get_attachment_url($img_id);
            echo '<img src="' . esc_url($img_url) . '" style="max-width:100px; margin:5px;">';
        }
    }
    echo '</div>';
    // 后续需要添加JavaScript实现图片上传和保存
}
// 保存meta
function save_gallery_meta($post_id) {
    if (!isset($_POST['article_gallery_nonce']) || !wp_verify_nonce($_POST['article_gallery_nonce'], 'article_gallery_nonce')) {
        return;
    }
    if (isset($_POST['article_gallery'])) {
        update_post_meta($post_id, '_article_gallery', $_POST['article_gallery']);
    }
}
add_action('save_post', 'save_gallery_meta');

