ap_total_posts_count( string $post_type = 'question', boolean|string $ap_type = false, false|int $user_id = false )

Description #

Return the total numbers of post.

Parameters #

  • $post_type
    string (Optional) Post type. Default value: 'question'
  • $ap_type
    boolean | string (Optional) ap_meta type. Default value: false
  • $user_id
    false | int (Optional) User id, default is current user id. Default value: false

Changelog #

VersionDescription
2.0.0Introduced.

Source #

File: includes/functions.php

function ap_total_posts_count( $post_type = 'question', $ap_type = false, $user_id = false ) {
	global $wpdb;

	if ( 'question' === $post_type ) {
		$type = "p.post_type = 'question'";
	} elseif ( 'answer' === $post_type ) {
		$type = "p.post_type = 'answer'";
	} else {
		$type = "(p.post_type = 'question' OR p.post_type = 'answer')";
	}

	$meta = '';
	$join = '';

	if ( 'flag' === $ap_type ) {
		$meta = 'AND qameta.flags > 0';
		$join = "INNER JOIN {$wpdb->ap_qameta} qameta ON p.ID = qameta.post_id";
	} elseif ( 'unanswered' === $ap_type ) {
		$meta = 'AND qameta.answers = 0';
		$join = "INNER JOIN {$wpdb->ap_qameta} qameta ON p.ID = qameta.post_id";
	} elseif ( 'best_answer' === $ap_type ) {
		$meta = 'AND qameta.selected > 0';
		$join = "INNER JOIN {$wpdb->ap_qameta} qameta ON p.ID = qameta.post_id";
	}

	$where = "WHERE p.post_status NOT IN ('trash', 'draft') AND $type $meta";

	if ( false !== $user_id && (int) $user_id > 0 ) {
		$where .= ' AND p.post_author = ' . (int) $user_id;
	}

	$where = apply_filters( 'ap_total_posts_count', $where );
	$query = "SELECT count(*) as count, p.post_status FROM $wpdb->posts p $join $where GROUP BY p.post_status";

	$count = $wpdb->get_results( $query, ARRAY_A ); // @codingStandardsIgnoreLine
	$counts = array();

	foreach ( (array) get_post_stati() as $state ) {
		$counts[ $state ] = 0;
	}

	$counts['total'] = 0;

	if ( ! empty( $count ) ) {
		foreach ( $count as $row ) {
			$counts[ $row['post_status'] ] = (int) $row['count'];
			$counts['total']              += (int) $row['count'];
		}
	}

	return (object) $counts;
}

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Add your comment