在WooCommerce产品类别设置中为精选帖子添加多选字段

时间:2019-04-01 07:09:16

标签: php ajax wordpress woocommerce multi-select

我正在制作一个简单的插件,用户可以在其中为每个woocommerce产品类别选择自定义帖子或帖子列表。我正在使用<!DOCTYPE html> <head> <meta charset="utf-8"> <script src="https://unpkg.com/d3@5.9.1/dist/d3.min.js"></script> <style> body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } </style> </head> <body> <script> //add svg var svg = d3.select("body").append("svg") .attr("width", 960) .attr("height", 500) .attr('stoke', 'red'); //////////////GENERATEs AREA///////////// // //Append a defs var defs = svg.append("defs"); //Append a linearGradient element to the defs and give it a unique id var linearGradient = defs.append("linearGradient") .attr("id", "linear-gradient"); //Horizontal gradient linearGradient .attr("x1", "10%") .attr("y1", "0%") .attr("x2", "90%") .attr("y2", "0%"); linearGradient.append("stop") .attr("offset", "0%") .attr("stop-color", "#eff3ff"); linearGradient.append("stop") .attr("offset", "25%") .attr("stop-color", "#bdd7e7"); linearGradient.append("stop") .attr("offset", "50%") .attr("stop-color", "#6baed6"); linearGradient.append("stop") .attr("offset", "75%") .attr("stop-color", "#3182bd"); linearGradient.append("stop") .attr("offset", "100%") .attr("stop-color", "#08519c") .attr("stop-opacity", .8); var xScale = d3.scaleLinear() .domain([0, 8]) .range([0, +innerWidth]) var heightScale = d3.scaleLinear() .domain([0,4]) .range([(3/4) * innerHeight, 50]) //generate area points var areaX = [... Array(9).keys()].map(xScale) var areaY1 = [.75, .74, 1.25, 1.24, 1.75, 1.74, 2, 2.31, 2.39].map(e => e * (innerHeight/9)) var areaY0 = areaY1.map(e => innerHeight - e) //zip points into an array of arrays. areaPoints = [[areaX, areaY1, areaY0]...] var zip = (...rows) => [...rows[0]].map((_,c) => rows.map(row => row[c])); var areaPoints = zip(areaX, areaY1, areaY0); //creat and array of objects from the areaPoints array of arrays. var points = [] areaPoints.forEach(a => points.push({x:a[0], heigh:a[1], low:a[2]})) //areaGenerator var areaGenerator = d3.area() .x(d => +d.x) .y0(d => +d.low) .y1(d => +d.heigh) .curve(d3.curveCardinal); //render the area from the points array of objects var area = areaGenerator(points); d3.select('svg') .append('path') .attr('d', area) .attr('fill', "url(#linear-gradient)"); function draw_graph(region, data){ var yTrans = points[region]['heigh'] - points[0]['heigh'] var width = points[2]['x'] var height = points[region]['low'] - points[region]['heigh'] var xAxisTrans = yTrans + height + 40 // the rectangle var rect = svg.append('rect') .attr('x', points[0]['x']) .attr('y', points[0]['heigh']) .attr('height',height) .attr('width', width) .attr('stroke', 'red') .attr('fill', 'none') .attr("transform", `translate(${points[region]['x']},${yTrans})`)//<-- translate the //graph domain var dom = data // x and y scales var xScale = d3.scaleLinear() .domain(d3.extent(dom)) .range([0, width]) var yScale = d3.scalePoint() .domain(dom) .range([0, height]) // x and Y axis var xAxis = d3.axisBottom(xScale) var yAxis = d3.axisLeft(yScale) // x and y Axis Groups var xAxisG = svg.append('g') .call(xAxis) .attr("transform", `translate(${points[region]['x']},${xAxisTrans})`) var yAxisG = svg.append('g') .call(yAxis) .attr("transform", `translate(${points[region]['x']},${points[region]['heigh']})`) //render data as points svg.selectAll('circle').data(dom).enter() .append('circle') .attr('cx', d => xScale(d)) .attr('cy', d => yScale(d) + 40) .attr('r', 5) .attr("transform", `translate(${points[region]['x']},${yTrans})`)//<--translate points into rectangle } //Draw 4 graphs from 4 random arrays const com = [...Array(10)].map(_=>Math.ceil(Math.random()*40)) const vom = [...Array(50)].map(_=>Math.ceil(Math.random()*40)) const zom = [...Array(20)].map(_=>Math.ceil(Math.random()*40)) const jom = [...Array(20)].map(_=>Math.ceil(Math.random()*40)) draw_graph(0, com)//<--draw over the 1st region draw_graph(4, vom)//<--draw over the 3rd region draw_graph(2, zom)//<--draw over the 2nd region draw_graph(6, jom)//<--draw over the 4th region </script> </body>选择帖子列表 为什么不节省呢? 无法保存该字段的数据。 enter image description here

select2

1 个答案:

答案 0 :(得分:1)

主要问题是保存数据时(最后一个功能)。我主要回顾了您的最后2个功能,主要是最后一个功能:

// 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文件中。经过测试,可以正常工作。

enter image description here