【问题标题】:Interference of WordPress codesWordPress代码的干扰
【发布时间】:2022-11-15 02:49:28
【问题描述】:

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

//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 中,然后在您的模板中调用它们。但KIKO指出,这些都有些不完整。 return 不会向浏览器打印任何内容。您的 cmets 函数有一个 echo,但您没有调用该函数。编辑您的代码编辑使它变得更糟 - site_total_comment_count() 已经 echoes。你不需要在调用它时回显它。

标签: php wordpress woocommerce


【解决方案1】:

您可以创建一个custom shortcode

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

【讨论】:

    猜你喜欢
    • 2011-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-04
    • 2014-11-27
    • 2017-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多