admin管理员组文章数量:1415484
I'm new to PHP. I want to create a shortcode that outputs a user's order number, but I'm having trouble.
All I know is that the order ID variable is "$order->get_id();"
I'm new to PHP. I want to create a shortcode that outputs a user's order number, but I'm having trouble.
All I know is that the order ID variable is "$order->get_id();"
Share Improve this question asked Aug 19, 2019 at 3:58 MariaMaria 194 bronze badges 1 |1 Answer
Reset to default 1Would need to know how you are planning to use this shortcode because doing what you are asking raises the issue of what you want the shortcode to do if the user has multiple orders?
If this shortcode is going to be displayed on a page or post that is specific to a specific order then the shortcode can be created as follows:
The following two functions should be in your themes functions.php file or in your plugins main php file.
This registers your shortcode:
function register_my_shortcode() {
add_shortcode( 'get_current_order_number', 'get_current_order_number_callback' ) );
}
add_action( 'init', 'register_my_shortcode', 10 );
This is the function callback that builds what you want to do with your shortcode:
function get_current_order_number_callback( $atts ) {
// This is where you can get your order number.
global $post;
$order = new WC_Order($post->ID);
$output = '';
// Good to do a check that the order number is not empty.
if ( ! empty( $order->get_order_number() ) ) :
// This is where you can declare attributes that you can add in your shortcode.
$atts = shortcode_atts( array(
'id' => 'default-id',
'container_class' => 'default-container-class',
'class' => 'default-class',
), $atts );
// Now you can build the elements that you want to display the order number in.
$output .= '<div class="' . $atts['container_class'] . '">;
$output .= '<span id="' . $atts['id'] . '" class="' . $atts['class'] . '">' . $order->get_order_number() . '</span>';
$output .= '</div>';
// If order number is not empty will return your shortcode build above.
return $output;
endif;
// If order number is empty will return false.
return false;
}
Your shortcode will look like this and with no atts will use your defaults:
[get_current_order_number]
or with atts added:
[get_current_order_number id="43" container_class="custom-container" class="order-number-text"]
本文标签: Creating a shortcode with a variable (Woocommerce)
版权声明:本文标题:Creating a shortcode with a variable (Woocommerce)? 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745233422a2648921.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
$order
doesn't just exist, you have to get it from somewhere. In the case of WooCommerce, users can have many orders, so what order are you using? How are you getting it? Where is the shortcode going to be used? – Jacob Peattie Commented Aug 19, 2019 at 12:27