ap_insert_views( integer|boolean $ref_id, string $type = 'question', integer|false $user_id = false, string $ip = false )

Description #

Insert view data in ap_meta table and update qameta.

Parameters #

  • $ref_id
    integer | boolean (Required) Reference ID.
  • $type
    string (Optional) View type, default is question. Default value: 'question'
  • $user_id
    integer | false (Optional) User ID. Default value: false
  • $ip
    string (Optional) IP address. Default value: false

Source #

File: includes/views.php

function ap_insert_views( $ref_id, $type = 'question', $user_id = false, $ip = false ) {
	global $wpdb;

	if ( empty( $ref_id ) ) {
		return false;
	}

	if ( false === $user_id ) {
		$user_id = get_current_user_id();
	}

	if ( false === $ip || false === filter_var( $ip, FILTER_VALIDATE_IP ) ) {
		$ip = ! empty( $_SERVER['REMOTE_ADDR'] ) ? filter_var( wp_unslash( $_SERVER['REMOTE_ADDR'] ), FILTER_VALIDATE_IP ) : '';
	}

	// Insert to DB only if not viewed before and not anonymous.
	if ( ! empty( $user_id ) && ! ap_is_viewed( $ref_id, $user_id ) ) {
		$values = array(
			'view_user_id' => $user_id,
			'view_type'    => 'question',
			'view_ref_id'  => $ref_id,
			'view_ip'      => $ip,
			'view_date'    => current_time( 'mysql' ),
		);

		$insert = $wpdb->insert( $wpdb->ap_views, $values, array( '%d', '%s', '%d', '%s', '%s' ) ); // phpcs:ignore WordPress.DB

		if ( false !== $insert ) {

			/**
				* Trigger action after inserting a view.
				*
				* @param integer $view_id Newly inserted view id.
				*/
			do_action( 'ap_insert_view', $wpdb->insert_id );

			return $wpdb->insert_id;
		}
	}

	return false;
}

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