获取作者元图像的附件ID-附件元数据

时间:2016-07-26 作者:middlelady

我在用户配置文件中创建了一个自定义字段,用于上载配置文件图像。这很简单。

要创建我使用过的字段,请执行以下操作:

add_action( \'show_user_profile\', \'cover_image_function\' );
add_action( \'edit_user_profile\', \'cover_image_function\' );
function cover_image_function( $user ) 
{
   <h3>Cover Image</h3>
    <style type="text/css">
    .fh-profile-upload-options th,
    .fh-profile-upload-options td,
    .fh-profile-upload-options input {
        vertical-align: top;
    }
    .user-preview-image {
        display: block;
        height: auto;
        width: 300px;
    }
    </style>
    <table class="form-table fh-profile-upload-options">
        <tr>
            <th>
                <label for="image">Cover Image</label>
            </th>
            <td>
                <img class="user-preview-image" src="<?php echo esc_attr( get_the_author_meta( \'mycoverimage\', $user->ID ) ); ?>">
                <input type="text" name="mycoverimage" id="mycoverimage" value="<?php echo esc_attr( get_the_author_meta( \'mycoverimage\', $user->ID ) ); ?>" class="regular-text" />
                <input type=\'button\' class="button-primary" value="Upload Image" id="coverimage"/><br />
                <span class="description">Please upload your cover image.</span>
            </td>
        </tr>
    </table>
    <script type="text/javascript">
    (function( $ ) {
        $( \'input#coverimage\' ).on(\'click\', function() {
            tb_show(\'\', \'media-upload.php?type=image&TB_iframe=true\');

            window.send_to_editor = function( html ) 
            {
                imgurl = $( \'img\', html ).attr( \'src\' );
                $( \'#mycoverimage\' ).val(imgurl);
                tb_remove();
            }

            return false;
        });
    })(jQuery);
    </script>
}
要保存我的图像,请执行以下操作:

add_action( \'personal_options_update\', \'save_cover_image\' );
add_action( \'edit_user_profile_update\', \'save_cover_image\' );
function save_cover_image( $user_id ) {
    if ( !current_user_can( \'edit_user\', $user_id ) )
    {
        return false;
    }

    update_user_meta( $user_id, \'mycoverimage\', $_POST[ \'mycoverimage\' ] );
}
一切正常,但我无法找回attachment ID 用于生成thumbnails and smaller sizes. 目前,我只需获取如下url:

echo esc_attr( get_the_author_meta( \'mycoverimage\', $user->ID ) );
我甚至在其他问题中使用了已知的方法:

function get_attachment_id($image_url) {
    global $wpdb;
    $attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid=\'%s\';", $image_url )); 
    return $attachment[0]; 
}
但它不起作用。上载时,图像是否可能不生成任何附件元数据?我该怎么做?即使是已经回答的建议、文章或问题也将不胜感激。除了插件之外,我想构建一个自定义代码。谢谢

3 个回复
最合适的回答,由SO网友:middlelady 整理而成

我终于解决了!问题是

update_user_meta( $user_id, \'mycoverimage\', $_POST[ \'mycoverimage\' ] );
已保存图像,但未生成附件元数据。事实上,在我的桌子上usermeta id 这不是附件id。所以我不得不根据codex 使用wp_insert_attachment 例如:

add_action( \'personal_options_update\', \'save_cover_image\' );
add_action( \'edit_user_profile_update\', \'save_cover_image\' );
function save_cover_image( $user_id ) {
    if ( !current_user_can( \'edit_user\', $user_id ) )
    {
        return false;
    }
    $filename = $_POST[\'mycoverimage\'];
    $parent_post_id = 0;
    $filetype = wp_check_filetype( basename( $filename ), null );
    $wp_upload_dir = wp_upload_dir();
    $attachment = array(
        \'guid\'           => $wp_upload_dir[\'url\'] . \'/\' . basename( $filename ), 
        \'post_mime_type\' => $filetype[\'type\'],
        \'post_title\'     => preg_replace( \'/\\.[^.]+$/\', \'\', basename( $filename ) ),
        \'post_content\'   => \'\',
        \'post_status\'    => \'inherit\',
        \'post_author\'    => $uid
    );
    $attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );
    require_once( ABSPATH . \'wp-admin/includes/image.php\' );
    $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
    wp_update_attachment_metadata( $attach_id, $attach_data );
    update_user_meta( $user_id, \'mycoverimage\', $_POST[ \'mycoverimage\' ] );
}
在这一点上,我有一个usermeta idattachment id 我可以很容易地为拇指和其他操作检索。无论如何都要感谢@majick。

SO网友:cybmeta

我建议您使用更新的media manager对话框;WordPress将处理所有图像上传内容,包括生成中间大小和附加元数据。

这里是一个工作示例(这是一个根据以前的代码构建的快速示例,可能需要在生产中使用一些调整):

add_action( \'admin_enqueue_scripts\', \'load_wp_media_files\' );
function load_wp_media_files( $page ) {
  if( $page == \'profile.php\' || $page == \'user-edit.php\' ) {
    wp_enqueue_media();
    wp_enqueue_script( \'my_custom_script\', plugins_url( \'/js/myscript.js\' , __FILE__ ), array(\'jquery\'), \'0.1\' );
  }
}

add_action( \'show_user_profile\', \'cover_image_function\' );
add_action( \'edit_user_profile\', \'cover_image_function\' );
function cover_image_function( $user ) 
{
    $image_id = get_user_meta( $user->ID, \'mycoverimage\', true );
    if( intval( $image_id ) > 0 ) {
        // Change with the image size you want to use
        $image = wp_get_attachment_image( $image_id, \'medium\', false, array( \'id\' => \'user-preview-image\' ) );
    } else {
        $image = \'<img id="user-preview-image" src="https://some.default.image.jpg" />\';
    }
    ?>
   <h3>Cover Image</h3>
   <style type="text/css">
    .fh-profile-upload-options th,
    .fh-profile-upload-options td,
    .fh-profile-upload-options input {
        vertical-align: top;
    }
    .user-preview-image {
        display: block;
        height: auto;
        width: 300px;
    }
    </style>
    <table class="form-table fh-profile-upload-options">
        <tr>
            <th>
                <label for="image">Cover Image</label>
            </th>
            <td>
                <?php echo $image; ?>
                <input type="hidden" name="mycoverimage" id="mycoverimage" value="<?php echo esc_attr( get_the_author_meta( \'mycoverimage\', $user->ID ) ); ?>" class="regular-text" />
                <input type=\'button\' class="button-primary" value="Upload Image" id="coverimage"/><br />
                <span class="description">Please upload your cover image.</span>
            </td>
        </tr>
    </table>
    <?php
}

add_action( \'personal_options_update\', \'save_cover_image\' );
add_action( \'edit_user_profile_update\', \'save_cover_image\' );
function save_cover_image( $user_id ) {
    if ( ! current_user_can( \'edit_user\', $user_id ) )
    {
        return false;
    }

    update_user_meta( $user_id, \'mycoverimage\', $_POST[ \'mycoverimage\' ] );
}  


// Ajax action to refresh the user image
add_action( \'wp_ajax_cyb_get_image_url\', \'cyb_get_image_url\'   );
function cyb_get_image_url() {
    if(isset($_GET[\'id\']) ){
        $image = wp_get_attachment_image( filter_input( INPUT_GET, \'id\', FILTER_VALIDATE_INT ), \'medium\', false, array( \'id\' => \'user-preview-image\' ) );
        $data = array(
            \'image\'    => $image,
        );
        wp_send_json_success( $data );
    } else {
        wp_send_json_error();
    }
}
和myscript。js文件:

jQuery(document).ready( function($) {

      jQuery(\'input#coverimage\').click(function(e) {

             e.preventDefault();
             var image_frame;
             if(image_frame){
                 image_frame.open();
             }
             image_frame = wp.media({
                           title: \'Select Media\',
                           multiple : false,
                           library : {
                                type : \'image\',
                            }
                       });

                       image_frame.on(\'close\',function() {
                          // get selections and save to hidden input plus other AJAX stuff etc.
                          var selection =  image_frame.state().get(\'selection\');
                          var gallery_ids = new Array();
                          var my_index = 0;
                          selection.each(function(attachment) {
                             gallery_ids[my_index] = attachment[\'id\'];
                             my_index++;
                          });
                          var ids = gallery_ids.join(",");
                          jQuery(\'input#mycoverimage\').val(ids);
                          Refresh_Image(ids);
                       });

                      image_frame.on(\'open\',function() {
                        var selection =  image_frame.state().get(\'selection\');
                        ids = jQuery(\'input#mycoverimage\').val().split(\',\');
                        ids.forEach(function(id) {
                          attachment = wp.media.attachment(id);
                          attachment.fetch();
                          selection.add( attachment ? [ attachment ] : [] );
                        });

                      });

                    image_frame.on(\'toolbar:create:select\',function() {

                        image_frame.state().set(\'filterable\', \'uploaded\');

                    });

                    image_frame.open();
     });

});

function Refresh_Image(the_id){
        var data = {
            action: \'cyb_get_image_url\',
            id: the_id
        };

        jQuery.get(ajaxurl, data, function(response) {

            if(response.success === true) {
                jQuery(\'#user-preview-image\').replaceWith( response.data.image );
            }
        });
}
请注意this code stores image id on user meta field 与之前的全尺寸图像url不同,您可以从用户元字段中获取任意大小的图像:

$image_id = get_user_meta( $user->ID, \'mycoverimage\', true );
$fulle_user_image = wp_get_attachment_image( $image_id, \'full\' );

SO网友:majick

不确定这会有什么不同,但因为你只想得到一个值get_var 而不是get_col. 我稍微调整了查询,使其符合我所知道的效果:

function get_attachment_id($image_url) {
    global $wpdb;
    $attachment = $wpdb->get_var($wpdb->prepare("SELECT ID FROM ".$wpdb->prefix."posts WHERE post_type=\'attachment\' AND guid=\'%s\'", $image_url )); 
    return $attachment; 
}
利用你没有做的esc_attr 在将URL值发送到函数之前,请在URL值上单击,否则它将与它不匹配。

EDIT 您可以尝试将URL路径与guid 而不是完整的URL:

function get_attachment_id($image_url) {
    $parseurl = parse_url($image_url);
    $path = $parseurl[\'path\'];

    global $wpdb;
    $attachments = $wpdb->get_results("SELECT ID,guid FROM ".$wpdb->prefix."posts WHERE post_type=\'attachment\'");
    foreach ($attachments as $attachment) {
        if (strstr($attachment->guid,$path)) {return $attachment->ID;}
    }
    echo "<!-- All Attachments "; print_r($attachments); echo "-->"; // debug output
}

相关推荐

插件“WP Attachments”在_Content之后输出,我怎样才能最好地更改位置?

我正在使用插件;WP附件;在帖子上显示附加的媒体文件。该插件似乎无法在我的模板中手动调用列表,我认为该插件不再受到支持。我签入了插件代码,我认为下面这行是关键。add_filter(\'the_content\', \'wpatt_content_filter\'); 我的编码能力有限,但我基本上将“内容”更改为“附件文件”,并在我的函数中进行了更改。我添加的php:function the_attachedfiles( $more_link_text = null, $strip_teaser