在Metabox中添加上传按钮

时间:2013-08-07 作者:Azad Rana

我想为图像添加上传图像按钮并检索url。谁能帮帮我,我已经试了好几天了。我正在使用此线程中的代码Create more Meta Boxes as needed.

add_action( \'add_meta_boxes\', \'dynamic_add_custom_box\' );

/* Do something with the data entered */
add_action( \'save_post\', \'dynamic_save_postdata\' );

/* Adds a box to the main column on the Post and Page edit screens */
function dynamic_add_custom_box() {
    add_meta_box(
        \'dynamic_sectionid\',
        __( \'Client Information\', \'myplugin_textdomain\' ),
        \'dynamic_inner_custom_box\',
        \'page\');
}

/* Prints the box content */
function dynamic_inner_custom_box() {
    global $post;
    // Use nonce for verification
    wp_nonce_field( plugin_basename( __FILE__ ), \'dynamicMeta_noncename\' );
    ?>
    <div id="meta_inner">
    <?php

    //get the saved meta as an arry
    $ourwork = get_post_meta($post->ID,\'ourwork\',true);

    $c = 0;
    if ( is_array( $ourwork ) ) {
        foreach( $ourwork as  $track ) {
            if ( isset( $track[\'thumb\'] ) || isset( $track[\'client-img1\'] ) || isset( $track[\'client-img2\'] ) || isset( $track[\'client-img3\'] ) || isset( $track[\'client-img4\'] ) || isset( $track[\'client-desc\'] ) ) {
                printf( \'<p><strong>Thumb Image</strong> &nbsp;:&nbsp;<input type="button" name="ourwork[%1$s][thumb]" value="%2$s" size="50" /><br/><br/><strong>Client Image 1</strong> : <input type="button" name="ourwork[%1$s][client-img1]" value="%3$s" size="50" /><br/><br/>
                <strong>Client Image 2</strong> : <input type="button" name="ourwork[%1$s][client-img2]" value="%4$s" size="50"/><br/><br/>
                <strong>Client Image 3</strong> : <input type="button" name="ourwork[%1$s][client-img3]" value="%5$s" size="50" /><br/><br/>
                <strong>Client Image 4</strong> : <input type="button" name="ourwork[%1$s][client-img4]" value="%6$s" size="50" />
                <br/><br/>
                <strong>Client Link &nbsp;&nbsp;&nbsp;&nbsp;1</strong> : <input type="text" name="ourwork[%1$s][client-link1]" value="%7$s" size="50" />
                <br/><br/>
                <strong>client Description</strong> :<br/><textarea id="elm1" class="tinymce_data" name="ourwork[%1$s][client-desc]" cols="75" rows="6" >%8$s</textarea><br/>
                <span class="remove">%9$s</span></p>\', $c, $track[\'thumb\'], $track[\'client-img1\'], $track[\'client-img2\'] , $track[\'client-img3\'], $track[\'client-img4\'], $track[\'client-link1\'], $track[\'client-desc\'],  __( \'<span class="button">Remove Section</span>\' ) );
                $c = $c +1;
            }
        }
    }
    ?>
<span id="here"></span>
<span class="add"><?php _e(\'<span class="button">Add Section</span>\'); ?></span>
<script>
    var $ =jQuery.noConflict();
    $(document).ready(function() {
        var count = <?php echo $c; ?>;
        $(".add").click(function() {
            count = count + 1;

            $(\'#here\').append(\'<p><strong>Thumb Image</strong> &nbsp;:&nbsp;<input type="button" name="ourwork[\'+count+\'][thumb]" value="" size="50"/><br/><br/><strong>Client Image 1</strong> : <input type="type="button"" name="ourwork[\'+count+\'][client-img1]" value="" size="50"/><br/><br/><strong>Client Image 2</strong> : <input type="button" name="ourwork[\'+count+\'][client-img2]" value="" size="50"/><br/><br/><strong>Client Image 3</strong> : <input type="type="button"" name="ourwork[\'+count+\'][client-img3]" value="" size="50"/><br/><br/><strong>Client Image 4</strong> : <input type="type="button"" name="ourwork[\'+count+\'][client-img4]" value="" size="50"/><br/><br/><strong>Client Link &nbsp;&nbsp;&nbsp;&nbsp;1</strong> : <input type="text" name="ourwork[\'+count+\'][client-link1]" value="" size="50"/><br/><br/><strong>Client Description</strong> :<br/><textarea id="elm1" name="ourwork[\'+count+\'][client-desc]" cols="75" rows="6"></textarea><br/><span class="remove"><span class="button">Remove Section</span></span></p>\' );
            return false;       
        });
        $(".remove").live(\'click\', function() {
            $(this).parent().remove();
        });
    });
    </script>
</div><?php

}

/* When the post is saved, saves our custom data */
function dynamic_save_postdata( $post_id ) {
    // verify if this is an auto save routine. 
    // If it is our form has not been submitted, so we dont want to do anything
    if ( defined( \'DOING_AUTOSAVE\' ) && DOING_AUTOSAVE ) 
        return $post_id;

    // verify this came from the our screen and with proper authorization,
    // because save_post can be triggered at other times
    if ( !isset( $_POST[\'dynamicMeta_noncename\'] ) )
        return;

    if ( !wp_verify_nonce( $_POST[\'dynamicMeta_noncename\'], plugin_basename( __FILE__ ) ) )
        return;

    // OK, we\'re authenticated: we need to find and save the data

    $ourwork = $_POST[\'ourwork\'];

    update_post_meta($post_id,\'ourwork\',$ourwork);
}

2 个回复
SO网友:eduardogoncalves

这是我在metabox中创建上载按钮的方法:

文件:template\\u dir/functions。php添加此行:

wp_enqueue_script(\'custom-js\', get_template_directory_uri().\'/js/custom-js.js\');

// Add the Meta Box  
function add_custom_meta_box() {  
    add_meta_box(  
        \'custom_meta_box\', // $id  
        \'Custom Meta Box\', // $title   
        \'show_custom_meta_box\', // $callback  
        \'post\', // $page  
        \'normal\', // $context  
        \'high\'); // $priority  
}  
add_action(\'add_meta_boxes\', \'add_custom_meta_box\');  

// Field Array  
$prefix = \'custom_\';  
$custom_meta_fields = array(
    array(  
        \'name\'  => \'Image\',  
        \'desc\'  => \'A description for the field.\',  
        \'id\'    => $prefix.\'image\',  
        \'type\'  => \'image\'  
    )  
);


// The Callback  
function show_custom_meta_box() {  
global $custom_meta_fields, $post;  
// Use nonce for verification  
echo \'\';  

    // Begin the field table and loop  
    echo \'\';  
    foreach ($custom_meta_fields as $field) {  
        // get value of this field if it exists for this post  
        $meta = get_post_meta($post->ID, $field[\'id\'], true);  
        // begin a table row with  
        echo \' 
                \'.$field[\'label\'].\' 
                \';  
                switch($field[\'type\']) {  
                    // case items will go here 
                        // image  
                        case \'image\':  
                            $image = get_template_directory_uri().\'/images/image.png\';    
                            echo \'\'.$image.\'\';  
                            if ($meta) { $image = wp_get_attachment_image_src($meta, \'medium\'); $image = $image[0]; }                 
                            echo    \' 
                                        
Remove Image \'.$field[\'desc\'].\'\'; break; } //end switch echo \'\'; } // end foreach echo \'\'; // end table } // Save the Data function save_custom_meta($post_id) { global $custom_meta_fields; // verify nonce if (!wp_verify_nonce($_POST[\'custom_meta_box_nonce\'], basename(__FILE__))) return $post_id; // check autosave if (defined(\'DOING_AUTOSAVE\') && DOING_AUTOSAVE) return $post_id; // check permissions if (\'page\' == $_POST[\'post_type\']) { if (!current_user_can(\'edit_page\', $post_id)) return $post_id; } elseif (!current_user_can(\'edit_post\', $post_id)) { return $post_id; } // loop through fields and save the data foreach ($custom_meta_fields as $field) { $old = get_post_meta($post_id, $field[\'id\'], true); $new = $_POST[$field[\'id\']]; if ($new && $new != $old) { update_post_meta($post_id, $field[\'id\'], $new); } elseif (\'\' == $new && $old) { delete_post_meta($post_id, $field[\'id\'], $old); } } // end foreach } add_action(\'save_post\', \'save_custom_meta\');

文件:template\\u dir/js/custom js。js公司

    jQuery(function(jQuery) {  

        jQuery(\'.custom_upload_image_button\').click(function() {  
            formfield = jQuery(this).siblings(\'.custom_upload_image\');  
            preview = jQuery(this).siblings(\'.custom_preview_image\');  
            tb_show(\'\', \'media-upload.php?type=image&TB_iframe=true\');  
            window.send_to_editor = function(html) {  
                imgurl = jQuery(\'img\',html).attr(\'src\');  
                classes = jQuery(\'img\', html).attr(\'class\');  
                id = classes.replace(/(.*?)wp-image-/, \'\');  
                formfield.val(imgurl);  //get image url and copy to field
                preview.attr(\'src\', imgurl);  
                tb_remove();  
            }  
            return false;  
        });  

        jQuery(\'.custom_clear_image_button\').click(function() {  
            var defaultImage = jQuery(this).parent().siblings(\'.custom_default_image\').text();  
            jQuery(this).parent().siblings(\'.custom_upload_image\').val(\'\');  
            jQuery(this).parent().siblings(\'.custom_preview_image\').attr(\'src\', defaultImage);  
            return false;  
        });  

    });  


如果您想添加更多类型的字段,可以通过以下网站了解更多信息:Reusable Custom Meta Boxes Part 1: Intro and Basic Fields

SO网友:MBL

有一个很好的与元数据库交互的框架,该框架相当容易使用(有很好的文档记录),并支持多个元数据库选项,包括图像/文件上传。在Github上:Custom Metaboxes and Fields (CMB). 如果要使用CMB,这将是实现上载字段的一种方法。

您需要注册文件上载metabox并向CMB添加呼叫init.php 在中使用以下代码functions.php 文件:

function be_sample_metaboxes( $meta_boxes ) {
    $prefix = \'_cmb_\'; // Prefix for all fields
    $meta_boxes[\'test_metabox\'] = array(
        \'id\' => \'test_metabox\',
        \'title\' => \'Test Metabox\',
        \'pages\' => array(\'post\'), // post type (e.g post, post etc.)
        \'context\' => \'normal\',
        \'priority\' => \'high\',
        \'show_names\' => true, // Show field names on the left
        \'fields\' => array(
            array(
                \'name\' => __( \'Test Image\', \'cmb\' ),
                \'desc\' => __( \'Upload an image or enter a URL.\', \'cmb\' ),
                \'id\'   => $prefix . \'test_image\',
                \'type\' => \'file\',
            ),
        ),
    );

    return $meta_boxes;
}
add_filter( \'cmb_meta_boxes\', \'be_sample_metaboxes\' );

// Initialize the metabox class
add_action( \'init\', \'be_initialize_cmb_meta_boxes\', 9999 );
function be_initialize_cmb_meta_boxes() {
    if ( !class_exists( \'cmb_Meta_Box\' ) ) {
        require_once( \'./metabox/init.php\' );
    }
}
生产线require_once( \'./metabox/init.php\' ); 在第二个函数中,假设您已将CMB元数据库中的文件放置在主题目录中的一个文件夹中,该文件夹名为metabox. 然后在模板中调用此选项(例如。single.php) 您可以使用以下功能

$file = get_post_meta( $post->ID, \'_cmb_test_image\', true );

结束