从CTP添加自定义WooCommerce下拉检出字段 [英] Adding custom WooCommerce dropdown checkout field from a CTP

查看:0
本文介绍了从CTP添加自定义WooCommerce下拉检出字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从我的自定义帖子类型fundraiser";中的所有帖子列表向我的WooCommerce结账页面添加一个下拉列表。

我显示了选择字段,但未填充CPT帖子标题的选项。

我做错了什么?以下是我的代码:

add_action( 'woocommerce_after_order_notes', 'fundraiser_checkout_field' ); 
function fundraiser_checkout_field( $checkout ) 
{ 
   
    $options  = array();
    $options[0] = "Please Select a Fundraiser";
    $posts = array();
    $args = array('post_type'=>'fundraiser', 'posts_per_page'=>-1,'order'=>'asc');
    $query = New WP_Query($args);
    if($query->have_posts()):while($query->have_posts()):$query->the_post();
        $id = $posts['post_title'];


    foreach($results as $result) {
        $options[$result->id] = $result->nome;
    }
    endwhile;endif;wp_reset_postdata();
    
    echo '<div id="fundraiser_checkout_field"><h2>' . __('Fundraiser') . '</h2>';

    woocommerce_form_field( 'fundraiser_field', array( 
        'type' => 'select', 
        'class' => array('fundraiser form-row-wide'), 
        'label' => __('Select a Fundraiser'), 
        'required' => true,
        'options'   =>  $options, 
    ), $checkout->get_value( 'fundraiser_field' ) );

    echo '</div>';
    
;
return $checkout;
}

推荐答案

  • 由于我没有使用您使用的自定义帖子类型,我的回答基于post type product,将$post_type = 'product';替换为$post_type = 'fundraiser';

  • 您的代码包含一些小错误,例如while循环中不需要foreach

function fundraiser_checkout_field( $checkout ) {
    // Empty array
    $options = array();
    
    // First value
    $options[0] = __( 'Please Select a Fundraiser', 'woocommerce' );
    
    // Post type
    $post_type = 'product';
    
    // Args
    $args = array(
        'post_type'      => $post_type,
        'posts_per_page' => -1,
        'order'          => 'asc'
    );
    
    // Query args
    $query = New WP_Query($args);
    
    // WP_Query loop
    if ( $query->have_posts() ): 
        while( $query->have_posts() ):
            $query->the_post();
            
            $options[ $query->post->ID ] = $query->post->post_title;

        endwhile;
        wp_reset_postdata();
    endif;
    
    // Output
    echo '<div id="fundraiser_checkout_field"><h2>' . __( 'Fundraiser', 'woocommerce' ) . '</h2>';

    woocommerce_form_field( 'fundraiser_field', array(
        'type'     => 'select', 
        'class'    => array('fundraiser form-row-wide'), 
        'label'    => __( 'Select a Fundraiser', 'woocommerce' ), 
        'required' => true,
        'options'  =>  $options, 
    ), $checkout->get_value( 'fundraiser_field' ) );

    echo '</div>';
}
add_action( 'woocommerce_after_order_notes', 'fundraiser_checkout_field', 10, 1 );

这篇关于从CTP添加自定义WooCommerce下拉检出字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆