Email::save_email_template_form()

Description #

Save email templates.

Changelog #

VersionDescription
4.1.0Introduced.

Source #

File: addons/email/email.php

	public function save_email_template_form() {
		$editing       = false;
		$template_slug = ap_sanitize_unslash( 'template', 'r' );
		$template_id   = (int) ap_opt( 'email_template_' . $template_slug );

		$form   = anspress()->get_form( 'email_template' );
		$values = $form->get_values();

		// Check nonce and is valid form.
		if ( ! $form->is_submitted() || ! current_user_can( 'manage_options' ) ) {
			ap_ajax_json(
				array(
					'success'  => false,
					'snackbar' => array( 'message' => __( 'Trying to cheat?!', 'anspress-question-answer' ) ),
				)
			);
		}

		$post_args = array(
			'post_title'   => $values['subject']['value'],
			'post_content' => $values['body']['value'],
		);

		$_post = get_post( $template_id );
		if ( $_post ) {
			$editing         = true;
			$post_args['ID'] = $_post->ID;
			// Check if valid post type and user can edit.
			if ( $_post && 'anspress_email' !== $_post->post_type ) {
				ap_ajax_json( 'something_wrong' );
			}
		}

		// Post status.
		$post_args['post_status'] = 'publish';

		if ( $form->have_errors() ) {
			ap_ajax_json(
				array(
					'success'       => false,
					'snackbar'      => array( 'message' => __( 'Unable to post answer.', 'anspress-question-answer' ) ),
					'form_errors'   => $form->errors,
					'fields_errors' => $form->get_fields_errors(),
				)
			);
		}

		if ( ! $editing ) {
			$post_args['post_type'] = 'anspress_email';
			$post_id                = wp_insert_post( $post_args, true );
		} else {
			$post_id = wp_update_post( $post_args, true );
		}

		// If error return and send error message.
		if ( is_wp_error( $post_id ) ) {
			ap_ajax_json(
				array(
					'success'  => false,
					'snackbar' => array(
						'message' => sprintf(
							// Translators: placeholder contain error message.
							__( 'Unable to save template. Error: %s', 'anspress-question-answer' ),
							$post_id->get_error_message()
						),
					),
				)
			);
		}

		ap_opt( 'email_template_' . $template_slug, $post_id );

		$form->after_save(
			false,
			array(
				'post_id' => $post_id,
			)
		);

		// Clear temporary images.
		if ( $post_id ) {
			ap_clear_unattached_media();
		}

		ap_ajax_json(
			array(
				'success'  => true,
				'snackbar' => array(
					'message' => __( 'Post updated successfully', 'anspress-question-answer' ),
				),
				'post_id'  => $post_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