给WordPress 文章自定义域添加一个文件上传按钮
效果如上图。
主要供自定义域使用,方便调用。废话不多,直接贴代码。
需要插入到functions.php文件的代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | // pianpai.com 添加上传面板 function aw_custom_meta_boxes( $post_type, $post ) { add_meta_box( 'aw-meta-box', __( '上传文件的面板' ), 'render_aw_meta_box', array('post'), 'normal', 'high' ); } add_action( 'add_meta_boxes', 'aw_custom_meta_boxes', 10, 2 ); function render_aw_meta_box($post) { $image = get_post_meta($post->ID, 'aw_custom_image', true); ?> <table> <tr> <td><a href="#" class="aw_upload_image_button button button-secondary"><?php _e('上传文件'); ?></a></td> <td><input type="text" name="aw_custom_image" id="aw_custom_image" value="<?php echo $image; ?>" style="width:700px;" /></td> </tr> </table> <?php } //调用js function aw_include_script() { if ( ! did_action( 'wp_enqueue_media' ) ) { wp_enqueue_media(); } wp_enqueue_script( 'awscript', get_stylesheet_directory_uri() . '/js/awscript.js', array('jquery'), null, false ); } add_action( 'admin_enqueue_scripts', 'aw_include_script' ); //保存 function aw_save_postdata($post_id) { if (array_key_exists('aw_custom_image', $_POST)) { update_post_meta( $post_id, 'aw_custom_image', $_POST['aw_custom_image'] ); } } add_action('save_post', 'aw_save_postdata'); |
JS代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | jQuery(function($){ $('body').on('click', '.aw_upload_image_button', function(e){ e.preventDefault(); var button = $(this), aw_uploader = wp.media({ title: 'Custom image', library : { uploadedTo : wp.media.view.settings.post.id, type : 'image' }, button: { text: 'Use this image' }, multiple: false }).on('select', function() { var attachment = aw_uploader.state().get('selection').first().toJSON(); $('#aw_custom_image').val(attachment.url); }) .open(); }); }); |
JS代码可以保存到你的JS目录。
上面的代码可用,注意下目录问题。
调用的时候
1 | get_post_meta($post->ID, 'aw_custom_image', true) |
参考自:https://artisansweb.net/adding-custom-image-button-with-media-uploader-in-wordpress/