从CTP添加自定义WooCommerce下拉检出字段

2022-09-03 00:00:00 php wordpress woocommerce checkout

我正在尝试从我的自定义帖子类型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 );

相关文章