AnsPress_Admin_Ajax::recount_views()

Description #

Recount question views.

Changelog #

VersionDescription
4.0.5Introduced.

Source #

File: admin/ajax.php

	public static function recount_views() {
		if ( ! anspress_verify_nonce( 'recount_views' ) || ! current_user_can( 'manage_options' ) ) {
			wp_die();
		}

		global $wpdb;

		$args = wp_parse_args(
			ap_sanitize_unslash( 'args', 'r', '' ),
			array(
				'fake_views' => false,
				'min_views'  => 100,
				'max_views'  => 200,
			)
		);

		$paged  = (int) ap_sanitize_unslash( 'paged', 'r', 0 );
		$offset = absint( $paged * 100 );

		$ids = $wpdb->get_col( "SELECT SQL_CALC_FOUND_ROWS ID FROM {$wpdb->posts} WHERE post_type = 'question' LIMIT {$offset},100" ); // phpcs:ignore WordPress.DB

		$total_found = $wpdb->get_var( 'SELECT FOUND_ROWS()' ); // phpcs:ignore WordPress.DB

		foreach ( (array) $ids as $id ) {
			$table_views  = (int) ap_get_views( $id );
			$qameta_views = (int) ap_get_post_field( 'views', $id );

			if ( $qameta_views < $table_views ) {
				$views = $table_views + $qameta_views;
			} else {
				$views = $qameta_views;
			}

			if ( $args['fake_views'] ) {
				$views = $views + ap_rand( $args['min_views'], $args['max_views'], 0.5 );
			}

			ap_update_views_count( $id, $views );
		}

		$done   = $offset + count( $ids );
		$remain = $total_found - ( $offset + count( $ids ) );

		$json = array(
			'success' => true,
			'total'   => $total_found,
			'remain'  => $remain,
			'el'      => '.ap-recount-views',
			// translators: %1 is total completed, %2 is total found count.
			'msg'     => sprintf( __( '%1$d done out of %2$d', 'anspress-question-answer' ), $done, $total_found ),
		);

		if ( $remain > 0 ) {
			$json['q'] = array(
				'action'  => 'ap_recount_views',
				'__nonce' => wp_create_nonce( 'recount_views' ),
				'paged'   => $paged + 1,
			);
		}

		ap_send_json( $json );
	}

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