Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/codeigniter/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript WordPress/woocommerce:在结账时添加下拉选项(您在哪里找到我们?)+;使用Chart.js创建仪表板_Javascript_Php_Wordpress_Woocommerce - Fatal编程技术网

Javascript WordPress/woocommerce:在结账时添加下拉选项(您在哪里找到我们?)+;使用Chart.js创建仪表板

Javascript WordPress/woocommerce:在结账时添加下拉选项(您在哪里找到我们?)+;使用Chart.js创建仪表板,javascript,php,wordpress,woocommerce,Javascript,Php,Wordpress,Woocommerce,我是PHP/JS新手,喜欢学习更多关于编码的知识。今天我需要你的帮助(请漂亮!) 我目前正在尝试在Woocommerce结账台上添加一个下拉选项,以便访问者可以说出他们在哪里找到我们。 因此,我使用了一个程序员已经编写的代码片段,并对其进行了一些调整。 我的网站和他的网站之间唯一不同的想法是,他使用了Polylang,而我不是(单语网站) 除了管理仪表板没有显示正确的信息外,其他一切都正常工作: 在我的订单中,我希望只有一个条目(1个“Boucheáoreille”)。不是那样 下面是我为得到

我是PHP/JS新手,喜欢学习更多关于编码的知识。今天我需要你的帮助(请漂亮!)

我目前正在尝试在Woocommerce结账台上添加一个下拉选项,以便访问者可以说出他们在哪里找到我们。 因此,我使用了一个程序员已经编写的代码片段,并对其进行了一些调整。 我的网站和他的网站之间唯一不同的想法是,他使用了Polylang,而我不是(单语网站)

除了管理仪表板没有显示正确的信息外,其他一切都正常工作:

在我的订单中,我希望只有一个条目(1个“Boucheáoreille”)。不是那样

下面是我为得到这个结果所做的:

FUNCTIONS.PHP

    /**

add_action('admin_enqueue_scripts', 'kantaloup_admin_enqueue');
function kantaloup_admin_enqueue()
{
    //wp_enqueue_style('kantaloup', get_template_directory_uri() . '/style.css');
    wp_enqueue_script('chart', get_stylesheet_directory_uri() . '/js/Chart.bundle.min.js');

}

 function get_order_references_fields($return = '')
{
    if($return == 'keys'){
        return array(
            ('Bouche à oreille'),
            ('Médias sociaux'),
            ('Moteurs de recherche (Google, Bing...)'),
            ('Livre/Magazine'),
            ('Partenaire'),
            ('Autre'),
        );
    }

    return array(
        ('Bouche à oreille') => 'Bouche à oreille',
        ('Médias sociaux') => 'Médias sociaux',
        ('Moteurs de recherche (Google, Bing...)') => 'Moteurs de recherche (Google, Bing...)',
        ('Livre/Magazine') => 'Livre/Magazine',
        ('Partenaire') => 'Partenaire',
        ('Autre') => 'Autre',
    );
}


/*
 * Checkout fields: Add
 */
add_action('woocommerce_checkout_fields', 'custom_fields_at_checkout');
function custom_fields_at_checkout($fields)
{

    $fields['billing']['referred_by'] = array(
        'label'     => __('Où nous avez-vous entendu parler de nous?'),
        'placeholder'   => '',
        'required'  => true,
        'class'     => array('referred-by-checkout-field-input form-row-wide'),
        'clear'     => true,
        'type' => 'select',
        'options' => get_order_references_fields()
    );

    return $fields;

}

/*
 * Checkout fields: Validate
 */
/*
add_action('woocommerce_checkout_process', 'custom_fields_at_checkout_validate');
function custom_fields_at_checkout_validate()
{
    if(! $_POST['referred-by']){
        wc_add_notice(__('Veuillez remplir le champ «Où nous avez-vous entendu parler de nous?»'), 'error');
    }
}
*/

/*
 * Checkout fields: Add to order meta
 */
add_action('woocommerce_checkout_update_order_meta', 'custom_fields_at_checkout_add_to_order_meta');
function custom_fields_at_checkout_add_to_order_meta($order_id)
{
    if(! empty($_POST['referred_by']) )
    {
        update_post_meta($order_id, 'referred_by', sanitize_text_field($_POST['referred_by']) );
    }
}

/*
 * Checkout fields: Add to order admin page
 */
add_action('woocommerce_admin_order_data_after_billing_address', 'custom_fields_at_checkout_add_to_order_admin_page', 10, 1);
function custom_fields_at_checkout_add_to_order_admin_page($order)
{
    echo '<p><strong>' . __('Où nous avez-vous entendu parler de nous?') . ' :</strong><br>' . get_post_meta($order->id, 'refered_by', true) . '</p>';
}

/*
 * Add admin page for support tab
 */

add_action('admin_menu', 'create_order_report_admin_menu');
function create_order_report_admin_menu()
{
    $title = "Rapport de références";
    add_menu_page($title, $title, 'manage_options', 'sales-type-report', 'sales_type_report', '', '3.1');

    function sales_type_report()
    {
        include(get_stylesheet_directory() . '/includes/admin/sales-report.php');
    }
}

/*
 * Get order references and return json object
 */
function get_order_references_json()
{
    $references = get_order_references_fields();

    /*
     * Build the labels
     */
    $the_labels = [];
    foreach($references as $slug => $label)
    {
        $the_labels[] = $label;
    }

    /*
     * Build the datasets
     */
    $the_datasets = [];
    $this_dataset = new stdClass();

    $this_dataset->label = ['Nombre de commandes'];
    $this_dataset->backgroundColor = ['#CFF09E', '#A8DBA8', '#79BD9A', '#3B8686', '#0B486B', '#1B6995', '#1E81B9', '#88AABD'];
    $this_dataset->borderColor = ['#CFF09E', '#A8DBA8', '#79BD9A', '#3B8686', '#0B486B', '#1B6995', '#1E81B9', '#88AABD'];
    $this_dataset->borderWidth = 2;

    $orders = get_posts(
        array(
            'post_type' => 'shop_order',
            'posts_per_page' => -1,
            'post_status' => 'closed, wc-on-hold'
        )
    );

    if( empty($orders) ) return;

    $the_datasets_bars = [];
    foreach($orders as $order){
        $reference_meta = get_post_meta($post->ID, 'referred_by', true);

        if(! empty($reference_meta) ){

            foreach($references as $slug => $label)
            {
                if($slug == $reference_meta){
                    $the_datasets_bars[$slug] = ! isset($the_datasets_bars[$slug]) ? 0 : ++$the_datasets_bars[$slug];
                }
            }
        }
    }

    $correct_order = get_order_references_fields('keys');
    $correctly_ordered_dataset_bars = array_merge(array_flip($correct_order), $the_datasets_bars);

    $this_dataset->data = array_values($correctly_ordered_dataset_bars);

    $the_datasets[] = $this_dataset;

    /*
     * Build the final array
     */
    $data = array(
        'labels' => $the_labels,
        'datasets' => $the_datasets
    );

    return json_encode($data);
}
/**
添加操作(“管理队列脚本”、“kantaloup管理队列”);
函数kantaloup_admin_enqueue()
{
//wp_enqueue_style('kantaloup',get_template_directory_uri()。/style.css');
wp_enqueue_脚本('chart',get_stylesheet_directory_uri()。/js/chart.bundle.min.js');
}
函数get\u order\u references\u字段($return='')
{
如果($return=='keys'){
返回数组(
('Boucheáoreille'),
('Médias sociaux'),
('Motours de recherche(谷歌,必应…),
(“Livre/Magazine”),
(“Partenaire”),
(‘Autre’),
);
}
返回数组(
('Boucheáoreille')=>'Boucheáoreille',
('Médias sociaux')=>'Médias sociaux',
('Moteurs de recherche(谷歌,Bing…)=>'Moteurs de recherche(谷歌,Bing…),
('Livre/Magazine')=>'Livre/Magazine',
('Partenaire')=>'Partenaire',
('Autre')=>'Autre',
);
}
/*
*签出字段:添加
*/
添加_操作('woocommerce_checkout_fields'、'custom_fields_at_checkout');
函数自定义字段在签出时($fields)
{
$fields['billing']['referenced_by']=array(
“label”=>(你是谁?),
'占位符'=>'',
“必需”=>true,
'class'=>array('refered-by-checkout-field-input form row-wide'),
“清除”=>正确,
'类型'=>'选择',
'options'=>get\u order\u references\u fields()
);
返回$fields;
}
/*
*签出字段:验证
*/
/*
添加操作('woocommerce\u checkout\u process'、'custom\u fields\u at\u checkout\u validate');
函数自定义\字段\在\签出\验证()处
{
如果(!$_POST[“推荐人]){
wc_添加_通知(uuuuuuuz remplir le champ«Oùnous avez vous entendu parler de nous?»,'error');
}
}
*/
/*
*签出字段:添加到订单元
*/
添加操作('woocommerce\u checkout\u update\u order\u meta'、'custom\u fields\u at\u checkout\u add\u to\u order\u meta');
函数自定义字段在签出时添加到订单元($order\u id)
{
如果(!空($_POST['refered_by']))
{
更新发布元数据($订单id,'引用人',清理文本字段($发布['引用人]);
}
}
/*
*签出字段:添加到订单管理页面
*/
添加操作(“在账单地址后添加商业、管理、订单、数据”、“在结帐处添加、添加到订单、管理页面”,10,1);
函数自定义字段在签出时添加到订单管理页面($order)
{
回显“”。“我们的意见是一致的。”:
”。获取帖子($order->id,'refered_by',true)。

; } /* *为“支持”选项卡添加管理页面 */ 添加操作(“管理菜单”、“创建订单”报告“管理菜单”); 函数创建\订单\报告\管理\菜单() { $title=“和谐关系”; 添加菜单页面($title,$title,'manage_options','sales type report','sales_type_report','3.1'); 功能销售类型报告() { include(get_stylesheet_directory()。/includes/admin/sales report.php'); } } /* *获取订单引用并返回json对象 */ 函数get\u order\u references\u json() { $references=get_order_references_fields(); /* *建立标签 */ $theu标签=[]; foreach($slug=>$label作为引用) { $theu labels[]=$label; } /* *建立数据集 */ $theu数据集=[]; $this_dataset=new stdClass(); $this_dataset->label=['Nombre de commandes']; $this#u dataset->backgroundColor=[#CFF09E'、#A8DBA8'、#79BD9A'、#3B8686'、#0B486B'、#1B6995'、#1E81B9'、#88AABD']; $this#u dataset->borderColor=['#CFF09E'、'A8DBA8'、'79BD9A'、'3B8686'、'0B486B'、'1B6995'、'1E81B9'、'88AABD'; $this_dataset->borderWidth=2; $orders=get_posts( 排列( “post_type”=>“shop_order”, “每页帖子数”=>-1, “post_状态”=>“关闭,wc暂停” ) ); if(空($orders))返回; $the_datasets_bars=[]; foreach($orders作为$order){ $reference\u meta=get\u post\u meta($post->ID,'refered\u by',true); 如果(!空($reference_meta)){ foreach($slug=>$label作为引用) { 如果($slug==$reference\u meta){ $the_datasets_bars[$slug]=!isset($the_datasets_bars[$slug])?0:+$the_datasets_bars[$slug]; } } } } $correct_order=get_order_references_字段('key'); $correct_ordered_dataset_bars=数组合并(数组翻转($correct_order),$the_dataset_bars); $this\u dataset->data=array\u values($this\u dataset\u bars顺序正确); $the_dataset[]=$this_dataset; /* *构建最终阵列 */ $data=数组( “标签”=>$这些标签, “数据集”=>$the_数据集 ); 返回json_encode($data); }
在includes/admin/sales-report.php中:

<style>
    .sep{
        margin:40px 0;
    }
    .excerpt:after {
        content: "";
        display: table;
        clear: both;
    }
    .excerpt img{
        display:block;
        margin: 30px 0;
        max-width: 1024px;
        width: auto;
        border: 1px solid #ddd;
        padding: 10px;
        background: #fff;
    }
    .top{
        float:right;
    }
    ol ol{
        margin-top: 10px;
    }
</style>

<script>
    (function($){
        $(document).ready(function () {

            var ctx = $('#the-sales-references-table');
            var myChart = new Chart(ctx, {
                type: 'bar',
                data: <?= get_order_references_json(); ?>,
                options: {
                    scales: {
                        yAxes: [{
                            ticks: {
                                beginAtZero: true
                            }
                        }]
                    }
                }
            });
        });
    }(jQuery));
</script>

<div class="wrap">
    <h1>Rapport des références sur les commandes</h1>

    <div class="wrap">
        <canvas id="the-sales-references-table"></canvas>
    </div>

    <? get_order_references_json(); ?>
</div>

九月{
利润率:40px0;
}
.摘录:之后{
内容:“;
显示:表格;
明确:两者皆有;
}
.摘自img{
显示:块;
利润率:30px0;
最大宽度:1024px;
宽度:自动;
边框:1px实心
<?php
/**
 * Plugin Name: My Plugin
 * Description: Custom features.
 * Version: 2019.1.0.0
 */

 /*
 * kantaloup enqueue
 */
add_action('admin_enqueue_scripts', 'kantaloup_admin_enqueue');
function kantaloup_admin_enqueue()
{
    //wp_enqueue_style('kantaloup', get_template_directory_uri() . '/style.css');
    wp_enqueue_script('chart', plugin_dir_url(__FILE__) . 'js/Chart.bundle.min.js');

    // FIX: need to pass the data to the client-side so they can be accessible via JS
    wp_localize_script('chart', 'test', array(
        'data' => get_order_references_json()
    ));
}

function get_order_references_fields($return = '')
{
    if($return == 'keys'){
        return array(
            ('Bouche à oreille'),
            ('Médias sociaux'),
            ('Moteurs de recherche (Google, Bing...)'),
            ('Livre/Magazine'),
            ('Partenaire'),
            ('Autre'),
        );
    }

    return array(
        ('Bouche à oreille') => 'Bouche à oreille',
        ('Médias sociaux') => 'Médias sociaux',
        ('Moteurs de recherche (Google, Bing...)') => 'Moteurs de recherche (Google, Bing...)',
        ('Livre/Magazine') => 'Livre/Magazine',
        ('Partenaire') => 'Partenaire',
        ('Autre') => 'Autre',
    );
}


/*
 * Checkout fields: Add
 */
add_action('woocommerce_checkout_fields', 'custom_fields_at_checkout');
function custom_fields_at_checkout($fields)
{

    $fields['billing']['referred_by'] = array(
        'label'     => __('Où nous avez-vous entendu parler de nous?'),
        'placeholder'   => '',
        'required'  => true,
        'class'     => array('referred-by-checkout-field-input form-row-wide'),
        'clear'     => true,
        'type' => 'select',
        'options' => get_order_references_fields()
    );

    return $fields;

}

/*
 * Checkout fields: Validate
 */
/*
add_action('woocommerce_checkout_process', 'custom_fields_at_checkout_validate');
function custom_fields_at_checkout_validate()
{
    if(! $_POST['referred-by']){
        wc_add_notice(__('Veuillez remplir le champ «Où nous avez-vous entendu parler de nous?»'), 'error');
    }
}
*/

/*
 * Checkout fields: Add to order meta
 */
add_action('woocommerce_checkout_update_order_meta', 'custom_fields_at_checkout_add_to_order_meta');
function custom_fields_at_checkout_add_to_order_meta($order_id)
{
    if(! empty($_POST['referred_by']) )
    {
        update_post_meta($order_id, 'referred_by', sanitize_text_field($_POST['referred_by']) );
    }
}

/*
 * Checkout fields: Add to order admin page
 */
add_action('woocommerce_admin_order_data_after_billing_address', 'custom_fields_at_checkout_add_to_order_admin_page', 10, 1);
function custom_fields_at_checkout_add_to_order_admin_page($order)
{
    // FIX: there was an error accessing $order->id; need to use the get_id() 
    echo '<p><strong>' . __('Où nous avez-vous entendu parler de nous?') . ' :</strong><br>' . get_post_meta($order->get_id(), 'referred_by', true) . '</p>';
}

/*
 * Add admin page for support tab
 */

add_action('admin_menu', 'create_order_report_admin_menu');
function create_order_report_admin_menu()
{
    $title = "Rapport de références";
    add_menu_page($title, $title, 'manage_options', 'sales-type-report', 'sales_type_report', '', '3.1');
}
// FIX: separated the function to be outside of the above function
function sales_type_report()
{
    include('includes/admin/sales-report.php');
}

/*
 * Get order references and return json object
 */
function get_order_references_json()
{
    $references = get_order_references_fields();

    /*
     * Build the labels
     */
    $the_labels = [];
    foreach($references as $slug => $label)
    {
        $the_labels[] = $label;
    }

    /*
     * Build the datasets
     */
    $the_datasets = [];
    $this_dataset = new stdClass();

    $this_dataset->label = ['Nombre de commandes'];
    $this_dataset->backgroundColor = ['#CFF09E', '#A8DBA8', '#79BD9A', '#3B8686', '#0B486B', '#1B6995', '#1E81B9', '#88AABD'];
    $this_dataset->borderColor = ['#CFF09E', '#A8DBA8', '#79BD9A', '#3B8686', '#0B486B', '#1B6995', '#1E81B9', '#88AABD'];
    $this_dataset->borderWidth = 2;

    $orders = get_posts(
        array(
            'post_type' => 'shop_order',
            'posts_per_page' => -1, // required to allow >5 results
            'post_status' => array_keys( wc_get_order_statuses() )
        )
    );

    // print_r($orders);

    if( empty($orders) ) return;

    // FIX: (fill in all keys; otherwise, we get the stair effect)
    $the_datasets_bars = array_fill_keys(array_keys($references), 0);

    foreach($orders as $order){
        // FIX: MUST be $order->ID (Post->ID), not 'id'
        $reference_meta = get_post_meta($order->ID, 'referred_by', true);
        echo $reference_meta . "\n";

        if(! empty($reference_meta) ){

            foreach($references as $slug => $label)
            {
                if($slug == $reference_meta){
                    $the_datasets_bars[$slug] = ! isset($the_datasets_bars[$slug]) ? 0 : ++$the_datasets_bars[$slug];
                }
            }
        }
    }

    // FIX: some debug logs
    echo "THE_DATASETS_BARS\n";
    print_r($the_datasets_bars);
    echo "\n";

    $correct_order = get_order_references_fields('keys');
    $correctly_ordered_dataset_bars = array_merge(array_flip($correct_order), $the_datasets_bars);

    $this_dataset->data = array_values($correctly_ordered_dataset_bars);

    $the_datasets[] = $this_dataset;

    /*
     * Build the final array
     */
    $data = array(
        'labels' => $the_labels,
        'datasets' => $the_datasets
    );

    // FIX: added JSON_UNESCAPED_UNICODE; otherwise, French accents are mishandled
    return json_encode($data, JSON_UNESCAPED_UNICODE);
}
<style>
    .sep{
        margin:40px 0;
    }
    .excerpt:after {
        content: "";
        display: table;
        clear: both;
    }
    .excerpt img{
        display:block;
        margin: 30px 0;
        max-width: 1024px;
        width: auto;
        border: 1px solid #ddd;
        padding: 10px;
        background: #fff;
    }
    .top{
        float:right;
    }
    ol ol{
        margin-top: 10px;
    }
</style>

<script>
    let $ = jQuery
    // FIX: the way this method was launched caused problems when loading in browser;
    // there were nested 'document.ready' functions
    $(function() {
        console.warn("data", test);

        var ctx = $('#the-sales-references-table');
        console.info(ctx);
        var myChart = new Chart(ctx[0].getContext('2d'), {
            type: 'bar',
            // FIX: parse data from the PHP-generated JS data variable
            data: JSON.parse(test.data),
            options: {
                scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero: true
                        }
                    }]
                }
            }
        });
    })
</script>

<div class="wrap">
    <h1>Rapport des références sur les commandes</h1>

    <div class="wrap">
        <canvas id="the-sales-references-table"></canvas>
    </div>

    <!-- FIX (remove the PHP function) -->
</div>