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

//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>

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

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

推荐答案

您可以创建一个custom shortcode.

在您的unctions.php文件中try 以下内容:

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]');将其添加到任何自定义模板

Php相关问答推荐

添加自定义Metabox到WooCommerce管理订单,启用HPOS

PHP Perl正则表达式—URL前面没有等号和可能的单引号或双引号

编写WooCommerce多步骤签出

PHP,ZipArchive删除一个空文件?

如何使用ms graph php sdk v2列出具有已知路径的DriveItem的子项

如何在函数中定位WooCommerce产品循环

创建一个新的可变产品及其属性以用于WooCommerce中的变体

如何在其他数组php中创建具有关联数组的数组

有没有办法像引用枚举一样引用注册表中的对象?

将 PHP 版本更改为 8.1,但 WordPress 认为我们正在使用版本 7.4?

调度程序不发送任何消息

使用 wp_footer 挂钩添加一些 CSS 不起作用

如何在PHP中对多个脚本调用进行排队?

如何用 php ML 解决这个问题?

在 GA4 Data API V1 Beta 中使用 inListFilter 过滤器时出错

php-http/discovery 插件 1.15.1 是否仍在使用自己的模块 destruct Contao 4.13 中的composer 安装?

如何使 Wordpress Woocommerce 自定义输入字段成为必填字段

为什么非贪婪匹配会消耗整个模式,即使后面跟着另一个非贪婪匹配

升级到 PHP 8.2:ksort 和 krsort 更改

服务器发送的事件:EventSource 抛出 MIME 错误