Home > Back-end >  Interference of WordPress codes
Interference of WordPress codes

Time:11-15

On my site, I intend to display the total number of posts and comments on the site, as well as the total number of purchases made from my site. The codes I wrote are as follows:

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

These codes work fine individually, but when I put all three on the target page, the stats show wrong.

Can you write me a code that shows the correct statistics of these three items from my site?

CodePudding user response:

You can create a custom shortcode.

Try out this in your functions.php file:

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
}

After that, this shortcode can be directly add it to your target page from the backend. You can also add it to any custom template by the use of do_shortcode('[custom_shortcode]');

  • Related