主要问题是您需要使用get_the_title()
而不是the_title()
在代码中,作为the_title()
已回显,无法设置为变量。
您似乎希望在WooCommerce结账页面的下拉(或单选按钮)字段中显示您的取货位置(自定义帖子类型)。
您也可以简单地使用get_posts()
功能如下:
add_action(\'woocommerce_after_order_notes\', \'custom_checkout_field\');
function custom_checkout_field( $checkout ) {
$pickup_points = (array) get_posts( array(
\'post_type\' => \'pickup-point\',
\'posts_per_page\' => -1,
\'post_status\' => \'publish\'
) );
if ( count( $pickup_points ) > 0 ) {
$available_locations = []; // Initializing
// Loop though each \'pickup-point\' WP_Post object
foreach ( $pickup_points as $pickup_point ) {
// Set current post title in the array
$available_locations[] = $pickup_point->post_title;
}
// testing output
var_dump ($available_locations);
}
}
或者如果你有
WP_Query
:
add_action(\'woocommerce_after_order_notes\', \'custom_checkout_field\');
function custom_checkout_field( $checkout ) {
// Custom query to pull in the pickup points.
$query = new WP_Query( array(
\'post_type\' => \'pickup-point\',
\'posts_per_page\' => -1,
\'post_status\' => \'publish\'
) );
$available_locations = []; // Initializing
// Check that we have query results.
if ( $query->have_posts() ) :
$available_locations = []; // Initializing
while ( $query->have_posts() ) : $query->the_post();
$available_locations[] = get_the_title(); // Set the current title in the array
endwhile;
// testing output
var_dump ($available_locations);
wp_reset_postdata();
endif;
}
两者应该以相同的方式工作。