WooCommerce 제품 카테고리 설정에서 추천 게시물에 대한 다중 선택 필드 추가

Firefog

사용자가 각 woocommerce 제품 카테고리에 대한 사용자 지정 게시물 또는 게시물 목록을 선택할 수있는 간단한 플러그인을 만들고 있습니다. select2게시물 목록 선택에 사용 하고 있습니다. 왜 저장되지 않습니까? 필드에 대한 데이터를 저장하지 못했습니다.여기에 이미지 설명 입력

<?php 
if ( ! defined( 'ABSPATH' ) ) {  exit;  }

/*----------------------------------------------------------------------
Adding Ajax Search for POSTS
-------------------------------------------------------------------------*/
function ex_get_posts_ajax_callback(){
 global $post;
    // we will pass post IDs and titles to this array
    $return = array();

    // you can use WP_Query, query_posts() or get_posts() here - it doesn't matter
    $search_results = new WP_Query( array( 
        's'=> $_GET['q'], // the search query
        'post_type' => 'post',//post type
        'post_status' => 'publish', // if you don't want drafts to be returned
        'ignore_sticky_posts' => 1,
        'posts_per_page' => 20 // how much to show at once
    ) );
    if( $search_results->have_posts() ) :
        while( $search_results->have_posts() ) : $search_results->the_post();   
            // shorten the title a little
            $title = ( mb_strlen( $search_results->post->post_title ) > 50 ) ? mb_substr( $search_results->post->post_title, 0, 49 ) . '...' : $search_results->post->post_title;
            $return[] = array( $search_results->post->ID, $title ); // array( Post ID, Post Title )
        endwhile;
    endif;
    wp_send_json( $return );
}
add_action( 'wp_ajax_getpostsearch', 'ex_get_posts_ajax_callback' ); // wp_ajax_{action}




//html output for edit field
function ex_product_cat_feature_posts($post_object) {
    global $post;
    // Nonce field to validate form request came from current site
    wp_nonce_field( basename( __FILE__ ), '_feature_post_nonce' );

    $html = '';

    // always array because we have added [] to our <select> name attribute
    $ex_product_cat_feature_post = get_post_meta( $post_object->ID, 'ex_product_cat_feature_post', true );

    $html .= '<tr class="form-field">';
    $html .= '<th scope="row" valign="top"><label for="catshort_button_type">Select Feature post:</label></th>';
    $html .= '<td>';
    $html .= '<select id="ex_product_cat_feature_post" name="ex_product_cat_feature_post[]" multiple="multiple" style="width:99%;max-width:25em;">';

    if( $ex_product_cat_feature_post ) {
        foreach( $ex_product_cat_feature_post as $post_id ) {
            $title = get_the_title( $post_id );
            // if the post title is too long, truncate it and add "..." at the end
            $title = ( mb_strlen( $title ) > 50 ) ? mb_substr( $title, 0, 49 ) . '...' : $title;
            $html .=  '<option value="' . $post_id . '" selected="selected">' . $title . '</option>';
        }
    }
    $html .= '</select>';
    $html .= '</td>';
    $html .= '</tr>';

    echo $html;
    //==========================================
    ?>
    <script>
    (function ($) {
        'use strict';
    $(function () {
        //--------------------------------------------------------------------------
        // multiple select with AJAX search
        $('#ex_product_cat_feature_post').select2({
            ajax: {
                    url: ajaxurl, // AJAX URL is predefined in WordPress admin
                    dataType: 'json',
                    delay: 250, // delay in ms while typing when to perform a AJAX search
                    data: function (params) {
                        return {
                            q: params.term, // search query
                            action: 'getpostsearch' // AJAX action for admin-ajax.php
                        };
                    },
                    processResults: function( data ) {
                    var options = [];
                    if ( data ) {

                        // data is the array of arrays, and each of them contains ID and the Label of the option
                        $.each( data, function( index, text ) { // do not forget that "index" is just auto incremented value
                            options.push( { id: text[0], text: text[1]  } );
                        });

                    }
                    return {
                        results: options
                    };
                },
                cache: true
            },
            minimumInputLength: 3 // the minimum of symbols to input before perform a search
        });

        //----------------------------------------------------------------------------------------
    });
})(jQuery);
</script>   
<style type="text/css">
     iframe#description_ifr{
            min-height:220px !important;
     }
</style>
    <?php 
}

add_action('product_cat_add_form_fields', 'ex_product_cat_feature_posts', 10, 1);
add_action('product_cat_edit_form_fields', 'ex_product_cat_feature_posts', 10, 1);


// Save extra taxonomy fields callback function.
function ex_product_cat_feature_posts_save($term_id) {
    $ex_product_cat_feature_post     = filter_input(INPUT_POST, 'ex_product_cat_feature_post');

    update_term_meta($term_id, 'ex_product_cat_feature_post', $ex_product_cat_feature_post);
}

add_action('edited_product_cat', 'ex_product_cat_feature_posts_save', 10, 1);
add_action('create_product_cat', 'ex_product_cat_feature_posts_save', 10, 1);
LoicTheAztec

가장 큰 문제는 데이터를 저장할 때입니다 (마지막 기능). 나는 주로 마지막 두 가지 기능, 대부분 마지막 기능을 다시 방문했습니다.

// Adding Ajax Search for POSTS - wp_ajax_{action}
add_action( 'wp_ajax_getpostsearch', 'ex_get_posts_ajax_callback' );
function ex_get_posts_ajax_callback(){
    $return = array(); // we will pass post IDs and titles to this array

    // You can use WP_Query, query_posts() or get_posts() here - it doesn't matter
    $search_results = new WP_Query( array(
        's'=> $_GET['q'], // the search query
        'post_type' => 'post',//post type
        'post_status' => 'publish', // if you don't want drafts to be returned
        'ignore_sticky_posts' => 1,
        'posts_per_page' => 20 // how much to show at once
    ) );
    if( $search_results->have_posts() ) :
        while( $search_results->have_posts() ) : $search_results->the_post();
            // shorten the title a little
            $title = ( mb_strlen( $search_results->post->post_title ) > 50 ) ? mb_substr( $search_results->post->post_title, 0, 49 ) . '...' : $search_results->post->post_title;
            $return[] = array( $search_results->post->ID, $title ); // array( Post ID, Post Title )
        endwhile;
    endif;
    wp_send_json( $return );
}

// {$taxonomy}_add_form_fields

// HTML output for edit field
add_action('product_cat_add_form_fields', 'ex_product_cat_feature_posts', 10, 1);
add_action('product_cat_edit_form_fields', 'ex_product_cat_feature_posts', 10, 1);
function ex_product_cat_feature_posts( $taxonomy ) {
    // Nonce field to validate form request came from current site
    wp_nonce_field( basename( __FILE__ ), '_feature_post_nonce' );

    $html  = '<tr class="form-field">
    <th scope="row" valign="top"><label for="catshort_button_type">Select Feature post:</label></th>
    <td>
        <select id="ex_product_cat_feature_post" name="ex_product_cat_feature_post[]" multiple="multiple" style="width:99%;max-width:25em;">';

    $term_id = isset($_GET['tag_ID']) ? $_GET['tag_ID'] : '';

    if( $feature_post_ids = get_term_meta( $term_id, 'ex_product_cat_feature_post', true ) ) {
        foreach( $feature_post_ids as $post_id ) {
            $title = get_the_title( $post_id );
            // if the post title is too long, truncate it and add "..." at the end
            $title = ( mb_strlen( $title ) > 50 ) ? mb_substr( $title, 0, 49 ) . '...' : $title;
            $html .=  '<option value="' . $post_id . '" selected="selected">' . $title . '</option>';
        }
    }
    $html .= '</select></td></tr>';

    // CSS Output
    ?><style type="text/css">iframe#description_ifr {min-height:220px !important;}</style><?php

    // HTML Output
    echo $html;

    // jQuery Output
    ?><script>
    // multiple select with AJAX search
    jQuery(function($) {
        $('#ex_product_cat_feature_post').select2({
            ajax: {
                url: ajaxurl, // AJAX URL is predefined in WordPress admin
                dataType: 'json',
                delay: 250, // delay in ms while typing when to perform a AJAX search
                data: function (params) {
                    return {
                        q: params.term, // search query
                        action: 'getpostsearch' // AJAX action for admin-ajax.php
                    };
                },
                processResults: function( data ) {
                    var options = [];
                    if ( data ) {
                        // data is the array of arrays, and each of them contains ID and the Label of the option
                        $.each( data, function( index, text ) { // do not forget that "index" is just auto incremented value
                            options.push( { id: text[0], text: text[1]  } );
                        });
                    }
                    return {
                        results: options
                    };
                },
                cache: true
            },
            minimumInputLength: 3 // the minimum of symbols to input before perform a search
        });
    });
    </script>
    <?php
}

// edited_{$taxonomy}

// Save extra taxonomy fields callback function.
add_action( 'edited_product_cat', 'ex_product_cat_feature_posts_save', 10, 2 );
add_action( 'create_product_cat', 'ex_product_cat_feature_posts_save', 10, 2 );
function ex_product_cat_feature_posts_save( $term_id, $term_taxonomy_id ) {
    if( isset($_POST['ex_product_cat_feature_post']) && $feature_post_ids = $_POST['ex_product_cat_feature_post'] )
        update_term_meta($term_id, 'ex_product_cat_feature_post', $_POST['ex_product_cat_feature_post']);
}

코드는 활성 자식 테마 (또는 활성 테마)의 function.php 파일에 들어갑니다. 테스트 및 작동합니다.

여기에 이미지 설명 입력

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

WooCommerce 장바구니에 추가, 사용자 정의 선택 필드에서 두 번째 제품 추가

분류에서Dev

Woocommerce 카테고리에 따라 1 개의 제품 만 추가

분류에서Dev

제품 루프에 Wordpress / Woocommerce 제품 카테고리 추가 및 포장

분류에서Dev

제품 Prestashop에 카테고리 추가

분류에서Dev

카테고리에 대한 Laravel 다중 선택 필터, 하나의 선택 만 출력으로 가져옴

분류에서Dev

각 제품에 대한 WooCommerce Checkout에 수량 입력 필드 추가

분류에서Dev

카테고리에 따라 WooCommerce 제품 제목에 접두사 추가

분류에서Dev

특정 제품 카테고리에 대한 WooCommerce 제품 수량 설정 변경

분류에서Dev

특정 WooCommerce 제품 카테고리에 대한 속성 드롭 다운 숨기기

분류에서Dev

Magento 2 카테고리에 제품 추가 (코드)

분류에서Dev

선택한 WooCommerce 제품 변형 가격 이후 사용자 정의 필드 값 추가

분류에서Dev

woocommerce "완료된 주문"이메일에 가변 제품에 대한 "설명"필드 내용 추가

분류에서Dev

WooCommerce의 특정 사용자 역할에 대해 동일한 상위 카테고리의 장바구니 제품에 추가 허용

분류에서Dev

WooCommerce에서 사용자 정의 체크 아웃 선택 필드 추가 및 처리 문제

분류에서Dev

선택한 제품을 PHP의 테이블에 추가

분류에서Dev

Woocommerce에서 특정 제품 카테고리에 대한 장바구니 항목 가격 변경

분류에서Dev

WooCommerce product_page 단축 코드에 제품 제목에 대한 링크 추가

분류에서Dev

장바구니에 제품을 자동으로 추가 할 때 특정 카테고리 제외 WooCommerce

분류에서Dev

WooCommerce : 판매시 추천 제품을 거짓으로 설정

분류에서Dev

WooCommerce : 판매시 추천 제품을 거짓으로 설정

분류에서Dev

WooCommerce 제품 카테고리 페이지 루프 내에서 게시물 수 가져 오기

분류에서Dev

WooCommerce에서 제품의 무게를 선택한 후 새로운 가격을 계산하고 보여줍니다.

분류에서Dev

Opencart : 특정 카테고리에 제품 추가

분류에서Dev

WooCommerce의 사용자 정의 유형에서 관리 제품에만 필드 추가

분류에서Dev

카테고리에서 Wordpress 최신 게시물 추천 이미지

분류에서Dev

MS Excel 꺾은 선형 차트에서 각 제품에 대해 서로 다른 가로 (카테고리) 레이블을 설정하는 방법

분류에서Dev

WooCommerce 3+의 특정 카테고리에 대한 후크를 통해 제품 가격 변경

분류에서Dev

제품 카테고리에 따라 WooCommerce 알림에 이메일 첨부 파일 추가

분류에서Dev

WooCommerce는 제품 제목에 제품 카테고리를 표시합니다.

Related 관련 기사

  1. 1

    WooCommerce 장바구니에 추가, 사용자 정의 선택 필드에서 두 번째 제품 추가

  2. 2

    Woocommerce 카테고리에 따라 1 개의 제품 만 추가

  3. 3

    제품 루프에 Wordpress / Woocommerce 제품 카테고리 추가 및 포장

  4. 4

    제품 Prestashop에 카테고리 추가

  5. 5

    카테고리에 대한 Laravel 다중 선택 필터, 하나의 선택 만 출력으로 가져옴

  6. 6

    각 제품에 대한 WooCommerce Checkout에 수량 입력 필드 추가

  7. 7

    카테고리에 따라 WooCommerce 제품 제목에 접두사 추가

  8. 8

    특정 제품 카테고리에 대한 WooCommerce 제품 수량 설정 변경

  9. 9

    특정 WooCommerce 제품 카테고리에 대한 속성 드롭 다운 숨기기

  10. 10

    Magento 2 카테고리에 제품 추가 (코드)

  11. 11

    선택한 WooCommerce 제품 변형 가격 이후 사용자 정의 필드 값 추가

  12. 12

    woocommerce "완료된 주문"이메일에 가변 제품에 대한 "설명"필드 내용 추가

  13. 13

    WooCommerce의 특정 사용자 역할에 대해 동일한 상위 카테고리의 장바구니 제품에 추가 허용

  14. 14

    WooCommerce에서 사용자 정의 체크 아웃 선택 필드 추가 및 처리 문제

  15. 15

    선택한 제품을 PHP의 테이블에 추가

  16. 16

    Woocommerce에서 특정 제품 카테고리에 대한 장바구니 항목 가격 변경

  17. 17

    WooCommerce product_page 단축 코드에 제품 제목에 대한 링크 추가

  18. 18

    장바구니에 제품을 자동으로 추가 할 때 특정 카테고리 제외 WooCommerce

  19. 19

    WooCommerce : 판매시 추천 제품을 거짓으로 설정

  20. 20

    WooCommerce : 판매시 추천 제품을 거짓으로 설정

  21. 21

    WooCommerce 제품 카테고리 페이지 루프 내에서 게시물 수 가져 오기

  22. 22

    WooCommerce에서 제품의 무게를 선택한 후 새로운 가격을 계산하고 보여줍니다.

  23. 23

    Opencart : 특정 카테고리에 제품 추가

  24. 24

    WooCommerce의 사용자 정의 유형에서 관리 제품에만 필드 추가

  25. 25

    카테고리에서 Wordpress 최신 게시물 추천 이미지

  26. 26

    MS Excel 꺾은 선형 차트에서 각 제품에 대해 서로 다른 가로 (카테고리) 레이블을 설정하는 방법

  27. 27

    WooCommerce 3+의 특정 카테고리에 대한 후크를 통해 제품 가격 변경

  28. 28

    제품 카테고리에 따라 WooCommerce 알림에 이메일 첨부 파일 추가

  29. 29

    WooCommerce는 제품 제목에 제품 카테고리를 표시합니다.

뜨겁다태그

보관