Wp_Helpers::select_posts_by_post_type()

Return all the specific fields of post type in ajax call


Source Source

File: src/integrations/wp/helpers/wp-helpers.php

	public function select_posts_by_post_type() {
		global $uncanny_automator;

		$uncanny_automator->utilities->ajax_auth_check( $_POST );
		$fields = [];
		if ( isset( $_POST ) && key_exists( 'value', $_POST ) && ! empty( $_POST['value'] ) ) {
			$post_type = sanitize_text_field( $_POST['value'] );

			$args       = array(
				'posts_per_page'   => 999,
				'orderby'          => 'title',
				'order'            => 'ASC',
				'post_type'        => $post_type,
				'post_status'      => 'publish',
				'suppress_filters' => true,
				'fields'           => array( 'ids', 'titles' ),
			);
			$posts_list = $uncanny_automator->helpers->recipe->options->wp_query( $args, false, __( 'Any post', 'uncanny-automator' ) );

			if ( ! empty( $posts_list ) ) {

				$post_type_label = get_post_type_object( $post_type )->labels->name;

				$fields[] = array(
					'value' => '-1',
					'text'  => sprintf( _x( 'Any %s', 'WordPress post type', 'uncanny-automator' ), strtolower( $post_type_label ) ),
				);
				foreach ( $posts_list as $post_id => $post_title ) {
					// Check if the post title is defined
					$post_title = ! empty( $post_title ) ? $post_title : sprintf( __( 'ID: %1$s (no title)', 'uncanny-automator' ), $post_id );

					$fields[] = array(
						'value' => $post_id,
						'text'  => $post_title,
					);
				}
			} else {
				$post_type_label = 'post';

				if ( $post_type != - 1 ) {
					$post_type_label = get_post_type_object( $post_type )->labels->name;
				}

				$fields[] = array(
					'value' => '-1',
					'text'  => sprintf( _x( 'Any %s', 'WordPress post type', 'uncanny-automator' ), strtolower( $post_type_label ) ),
				);
			}
		}
		echo wp_json_encode( $fields );
		die();
	}