0

This is my Ajax Handler function

function get_total_post(user_ID)
{
    jQuery.ajax({
        type: 'post',
        url: ajaxforall.ajaxurl,
        cache: false,
        data: {
        action: 'avg_num_of_views',
        userid : user_ID
        },

        success:function(data, textStatus, XMLHttpRequest){
            console.log(data);
        }, 
        error: function(MLHttpRequest, textStatus, errorThrown){
            alert(errorThrown);
        }
    });
}

My Ajax Handler Function to Calculate the Total No of Post Views(hopefully my terminology is correct):

function avg_num_of_views($author_id) {
        //$author = get_user_by( 'id', get_query_var( 'author' ) );
        //$author_id = $author->ID;
        $number_of_posts = cv_count_user_posts( $author_id );
        $sumViews = 0;
        $avgViews = 0;
        if( !$number_of_posts == 0){
            $args = array(
            'author'    => $author_id,
            'post_type' => array('communityposts','post','video'),
            'posts_per_page'=> -1
            );
            $author_query = new WP_Query( $args );

            if( $author_query->have_posts() ) : while( $author_query->have_posts() ) : $author_query->the_post();
                $sumViews += get_post_meta( get_the_ID(), 'cv_post_views_count', true );
            endwhile; endif;
            wp_reset_postdata();

            $avgViews = $sumViews / $number_of_posts;

            return $avgViews;
        }else{
            $value_return = "20";
            return $value_return;
        }
        die();
    }

I wanted to pass an Author Id through JavaScript in Ajax Handler function to get the desired result.

cv_count_user_posts( $author_id ) 

is the function which is used to calculate the total no. of posts including custom post types

function cv_count_user_posts( $userid, $post_type = array('post', 'communityposts','video' ) ) {
    if( empty( $userid ) )
       return false;

    // if we get there, great so all fine and ready to go
    $args = array(
        'post_type'    => $post_type,
        'author'     => $userid
    );

    $the_query = new WP_Query( $args );
    $user_post_count = $the_query->found_posts;
    return $user_post_count;
}
  • So, pass the author ID in the data array. What is the question? – s_ha_dum Jun 10 '15 at 21:39
  • I get it ! this is what i was missing. Thanks for pointing out – Harman Preet Jun 11 '15 at 15:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.