Activity_Helper::insert( array $args = array() )

Description #

Insert activity data into the database. $q_id argument cannot be left blank as it is required.

Parameters #

  • $args
    array (Optional) Arguments for insert query.
    • 'action'
      (string) Registered action key.
    • 'q_id'
      (integer) Question id. This is a required argument.
    • 'a_id'
      (integer) Answer id. This argument is optional.
    • 'c_id'
      (integer) Comment id. This argument is optional.
    • 'user_id'
      (integer) User id. This is optional.
    • 'date'
      (string) Date of activity. Current time is used by default.
    Default value: array()

Changelog #

VersionDescription
4.1.8Add GMT offset in current_time.
4.1.2Introduced.

Source #

File: includes/class/class-activity-helper.php

	public function insert( $args = array() ) {
		global $wpdb;

		$args = wp_parse_args(
			$args,
			array(
				'action'  => '',
				'q_id'    => 0,
				'a_id'    => 0,
				'c_id'    => 0,
				'user_id' => get_current_user_id(),
				'date'    => current_time( 'mysql', true ),
			)
		);

		// Check if question id exists.
		if ( empty( $args['q_id'] ) ) {
			return new WP_Error( 'question_id_empty', __( 'Question id is required.', 'anspress-question-answer' ) );
		}

		// Check if valid action.
		if ( ! $this->action_exists( $args['action'] ) ) {
			return new WP_Error( 'not_valid_action', __( 'Not a valid action', 'anspress-question-answer' ) );
		}

		// split date for validation.
		$mm         = substr( $args['date'], 5, 2 );
		$jj         = substr( $args['date'], 8, 2 );
		$aa         = substr( $args['date'], 0, 4 );
		$valid_date = wp_checkdate( $mm, $jj, $aa, $args['date'] );

		// Validate date.
		if ( ! $valid_date ) {
			return new WP_Error( 'invalid_date', __( 'Invalid date', 'anspress-question-answer' ) );
		}

		// Insert.
		$inserted = $wpdb->insert( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
			$this->table,
			array(
				'activity_action'  => $args['action'],
				'activity_q_id'    => $args['q_id'],
				'activity_a_id'    => $args['a_id'],
				'activity_c_id'    => $args['c_id'],
				'activity_user_id' => $args['user_id'],
				'activity_date'    => $args['date'],
			),
			array(
				'%s',
				'%d',
				'%d',
				'%d',
				'%d',
				'%s',
			)
		);

		if ( ! $inserted ) {
			return new WP_Error( 'insert_activity_failed', __( 'Failed to insert activity', 'anspress-question-answer' ) );
		}

		/**
		 * Hook called right after an activity get inserted to database.
		 *
		 * @param array $args  Insert arguments.
		 * @since 4.1.2
		 */
		do_action( 'ap_activity_inserted', $args );

		return $wpdb->insert_id;
	}

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