web-dev-qa-db-ja.com

BuddyPressの拡張プロファイルフィールドに画像フィールドを追加する方法を教えてください。

BuddyPressの拡張プロファイルコンポーネントを使用していますが、WordPressのユーザープロファイルに画像フィールドを追加したいと思います。テーマのfunctions.phpに追加してプラグインに "Image"オプションを挿入できるようなコードはありますか?

私はBuddyPressとWordPress Codexフォーラムを検索しましたが、コアファイルを編集せずにプラグインの操作を傍受するためのコードを見つけていません。

2
KalenGi

私はコアBuddyPressファイルを編集せずに画像タイプフィールドを追加する方法を考え出しました。解決策はテーマのfunctions.phpにプラグインの読み込み、表示、保存を阻止するコードを追加することを含みます。また、プロフィール画像をuploadsディレクトリのサブディレクトリに送るために、WordPressのアップロード場所を更新します。 完全な解決策はこちら です。

手順1.新しいフィールドタイプを追加します。

function bpd_add_new_xprofile_field_type($field_types){
    $image_field_type = array('image');
    $field_types = array_merge($field_types, $image_field_type);
    return $field_types;
}

add_filter( 'xprofile_field_types', 'bpd_add_new_xprofile_field_type' );

ステップ2. WordPress管理パネルで新しいフィールドタイプのレンダリングを処理します

function bpd_admin_render_new_xprofile_field_type($field, $echo = true){

    ob_start();
        switch ( $field->type ) {
            case 'image':
                ?>
                    <input type="file" name="<?php bp_the_profile_field_input_name() ?>" id="<?php bp_the_profile_field_input_name() ?>" value="" />
                <?php
                break;
            default :
                ?>
                    <p>Field type unrecognized</p>
                <?php
        }

        $output = ob_get_contents();
    ob_end_clean();

    if($echo){
        echo $output;
        return;
    }
    else{
        return $output;
    }

}

add_filter( 'xprofile_admin_field', 'bpd_admin_render_new_xprofile_field_type' );

ステップ3. WordPressフロントエンドで新しいフィールドタイプのレンダリングを処理する

function bpd_edit_render_new_xprofile_field($echo = true){

    if(empty ($echo)){
        $echo = true;
    }

    ob_start();
        if ( bp_get_the_profile_field_type() == 'image' ){
            $imageFieldInputName = bp_get_the_profile_field_input_name();
            $image = WP_CONTENT_URL . bp_get_the_profile_field_edit_value();

        ?>
                <label for="<?php bp_the_profile_field_input_name(); ?>"><?php bp_the_profile_field_name(); ?> <?php if ( bp_get_the_profile_field_is_required() ) : ?><?php _e( '(required)', 'buddypress' ); ?><?php endif; ?></label>
                <input type="file" name="<?php echo $imageFieldInputName; ?>" id="<?php echo $imageFieldInputName; ?>" value="" <?php if ( bp_get_the_profile_field_is_required() ) : ?>aria-required="true"<?php endif; ?>/>
                <img src="<?php echo $image; ?>" alt="<?php bp_the_profile_field_name(); ?>" />

        <?php

        } 

        $output = ob_get_contents();
    ob_end_clean();

    if($echo){
        echo $output;
        return;
    }
    else{
        return $output;
    }

}

add_action( 'bp_custom_profile_edit_fields', 'bpd_edit_render_new_xprofile_field' );

ステップ4. WordPressの登録済みフック機能にアクセスして、BuddyPressプロファイル保存ハンドラーを削除し、新しいものを挿入します。これは、BuddyPressに制御を戻す前にカスタムフィールドの保存を処理するために必要です。

function bpd_override_xprofile_screen_edit_profile(){
    $screen_edit_profile_priority = has_filter('bp_screens', 'xprofile_screen_edit_profile');

    if($screen_edit_profile_priority !== false){
        //Remove the default profile_edit handler
        remove_action( 'bp_screens', 'xprofile_screen_edit_profile', $screen_edit_profile_priority );

        //Install replalcement hook
        add_action( 'bp_screens', 'bpd_screen_edit_profile', $screen_edit_profile_priority );
    }
}

add_action( 'bp_actions', 'bpd_override_xprofile_screen_edit_profile', 10 );

ステップ5.カスタムフィールド保存機能を作成する

function bpd_screen_edit_profile(){

    if ( isset( $_POST['field_ids'] ) ) {
        if(wp_verify_nonce( $_POST['_wpnonce'], 'bp_xprofile_edit' )){

            $posted_field_ids = explode( ',', $_POST['field_ids'] );

            $post_action_found = false;
            $post_action = '';
            if (isset($_POST['action'])){
                $post_action_found = true;
                $post_action = $_POST['action'];

            }

            foreach ( (array)$posted_field_ids as $field_id ) {
                $field_name = 'field_' . $field_id;

                if ( isset( $_FILES[$field_name] ) ) {
                    require_once( ABSPATH . '/wp-admin/includes/file.php' );
                    $uploaded_file = $_FILES[$field_name]['tmp_name'];

                    // Filter the upload location
                    add_filter( 'upload_dir', 'bpd_profile_upload_dir', 10, 1 );

                    //ensure WP accepts the upload job
                    $_POST['action'] = 'wp_handle_upload';

                    $uploaded_file = wp_handle_upload( $_FILES[$field_name] );

                    $uploaded_file = str_replace(WP_CONTENT_URL, '', $uploaded_file['url']) ;

                    $_POST[$field_name] = $uploaded_file;

                }
            }

            if($post_action_found){
                $_POST['action'] = $post_action;
            }
            else{
                unset($_POST['action']);
            }

        }
    }

    if(!defined('DOING_AJAX')){
        if(function_exists('xprofile_screen_edit_profile')){
            xprofile_screen_edit_profile();
        }
    }

}

ステップ6. WordPressのアップロードディレクトリの場所を上書きして、カスタムの画像保存場所を指定する

function bpd_profile_upload_dir( $upload_dir ) {
    global $bp;

    $user_id = $bp->displayed_user->id;
    $profile_subdir = '/profiles/' . $user_id;

    $upload_dir['path'] = $upload_dir['basedir'] . $profile_subdir;
    $upload_dir['url'] = $upload_dir['baseurl'] . $profile_subdir;
    $upload_dir['subdir'] = $profile_subdir;

    return $upload_dir;
}

手順7.プロファイルフロントエンドが表示されたときに新しいフィールドタイプを挿入するためにフィールドタイプ選択ドロップダウンを更新するためのコードを保持するJavaScriptファイルを作成します。ファイルxprofile-image.jsを呼び出して、テーマのfunctions.phpと同じ場所に保存しましょう。

(

    function(jQ){
        //outerHTML method (http://stackoverflow.com/a/5259788/212076)
        jQ.fn.outerHTML = function() {
            $t = jQ(this);
            if( "outerHTML" in $t[0] ){
                return $t[0].outerHTML;
            }
            else
            {
                var content = $t.wrap('<div></div>').parent().html();
                $t.unwrap();
                return content;
            }
        }

        bpd =
        {

        init : function(){

                //add image field type on Add/Edit Xprofile field admin screen
               if(jQ("div#poststuff select#fieldtype").html() !== null){

                    if(jQ('div#poststuff select#fieldtype option[value="image"]').html() === null){
                        var imageOption = '<option value="image">Image</option>';
                        jQ("div#poststuff select#fieldtype").append(imageOption);

                        var selectedOption = jQ("div#poststuff select#fieldtype").find("option:selected");
                        if((selectedOption.length == 0) || (selectedOption.outerHTML().search(/selected/i) < 0)){
                            var action = jQ("div#poststuff").parent().attr("action");

                            if (action.search(/mode=edit_field/i) >= 0){
                                jQ('div#poststuff select#fieldtype option[value="image"]').attr("selected", "selected");
                            }
                        }
                    }

                }

            }
        };

        jQ(document).ready(function(){
                bpd.init();
        });

    }

)(jQuery);

ステップ8. jsファイルをロードする(xprofile-image.js)

function bpd_load_js() {
     wp_enqueue_script( 'bpd-js', get_bloginfo('stylesheet_directory') . '/xprofile-image.js',
                            array( 'jquery' ), '1.0' );
}

add_action( 'wp_print_scripts', 'bpd_load_js' );

それでおしまい! WordPressのユーザープロファイルは、BuddyPressの拡張プロファイルコンポーネントを介して追加の画像フィールドをサポートするようになりました。

それがプラグインに変わることができればこれは本当に役に立ちます。

アップデート:私はプラグインを作成することに慣れ、それは WordPressプラグイン のページから入手できます。

2
KalenGi