WordPress代码干扰



在我的网站上,我打算显示网站上的帖子和评论的总数,以及从我的网站上购买的总数。我写的代码如下:

//copy to functions.php
// Total Comment 
function site_total_comment_count() {
$num_comm = get_comment_count();
$num_comm = $num_comm['total_comments'];
echo $num_comm  ;}
add_shortcode('total_comment_count', 'site_total_comment_count');


// Total Completed Orders
function total_completed_Orders() {
$query = new WC_Order_Query( array(
'limit' => 99999,
'status'        => array( 'completed' ),
'return' => 'ids',
) );
$orders = $query->get_orders();
return count( $orders ); }



// Copy to the desired page
<h2> All Orders:
<?php echo total_completed_Orders(); ?>
</h2>

<h2> All Comments:
<?php echo site_total_comment_count(); ?>
</h2>

<h2> All Posts:
<?php
echo $wpdb->get_var("SELECT COUNT(ID) FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish'");
?>
</h2>

这些代码单独运行良好,但是当我将三个代码都放在目标页面上时,统计数据显示错误。

你能给我写一段代码,显示我网站上这三个项目的正确统计数据吗?

您可以创建自定义短代码。

在你的functions.php文件中试试:

add_shortcode('custom_shortcode', 'kb_get_details');
function kb_get_details()
{
//For total post.
global $wpdb;
$total_post = $wpdb->get_var("SELECT COUNT(ID) FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish'");
//For total comments.
$num_comm  = get_comment_count();
$total_cmt = $num_comm['total_comments'];
//For total orders.
$query = new WC_Order_Query(array(
'limit'  => 99999,
'status' => array('completed'),
'return' => 'ids',
));
$orders       = $query->get_orders();
$total_orders = count($orders);
?>
<h2>All Posts   : <?php esc_html_e($total_post); ?></h2>
<h2>All Comments: <?php esc_html_e($total_cmt); ?></h2>
<h2>All Orders  : <?php esc_html_e($total_orders); ?></h2>
<?php
}

之后,这个短代码可以直接从后端添加到目标页面。您还可以使用do_shortcode('[custom_shortcode]');

将它添加到任何自定义模板中。

最新更新