LLMS_AJAX_Handler::select2_query_posts()

Handle Select2 Search boxes for WordPress Posts by Post Type and Post Status.


Description Description


Return Return

(void)


Top ↑

Source Source

File: includes/class.llms.ajax.handler.php

	public static function select2_query_posts() {

		global $wpdb;

		// grab the search term if it exists.
		$term = llms_filter_input( INPUT_POST, 'term', FILTER_SANITIZE_STRING );

		// get the page.
		$page = llms_filter_input( INPUT_POST, 'page', FILTER_SANITIZE_NUMBER_INT );

		// Get post type(s).
		$post_type = sanitize_text_field( llms_filter_input( INPUT_POST, 'post_type', FILTER_SANITIZE_STRING ) );
		$post_types_array = explode( ',', $post_type );
		foreach ( $post_types_array as &$str ) {
			$str = "'" . esc_sql( trim( $str ) ) . "'";
		}
		$post_types = implode( ',', $post_types_array );

		// Get post status(es).
		$post_statuses       = llms_filter_input( INPUT_POST, 'post_statuses', FILTER_SANITIZE_STRING );
		$post_statuses       = empty( $post_statuses ) ? 'publish' : $post_statuses;
		$post_statuses_array = explode( ',', $post_statuses );
		foreach ( $post_statuses_array as &$str ) {
			$str = "'" . esc_sql( trim( $str ) ) . "'";
		}
		$post_statuses = implode( ',', $post_statuses_array );

		$limit = 30;
		$start = $limit * $page;

		if ( $term ) {
			$like = " AND post_title LIKE '%s'";
			$vars = array( '%' . $term . '%', $start, $limit );
		} else {
			$like = '';
			$vars = array( $start, $limit );
		}

		$posts = $wpdb->get_results( $wpdb->prepare(
			"SELECT ID, post_title, post_type
			 FROM $wpdb->posts
			 WHERE post_type IN ( $post_types )
			   AND post_status IN ( $post_statuses )
			       $like
			 ORDER BY post_title
			 LIMIT %d, %d
			",
			$vars
		) );

		$items = array();

		$grouping = ( count( $post_types_array ) > 1 );

		foreach ( $posts as $post ) {

			$item = array(
				'id' => $post->ID,
				'name' => $post->post_title . ' (' . __( 'ID#', 'lifterlms' ) . ' ' . $post->ID . ')',
			);

			if ( $grouping ) {

				// setup an object for the optgroup if it's not already set up
				if ( ! isset( $items[ $post->post_type ] ) ) {
					$obj = get_post_type_object( $post->post_type );
					$items[ $post->post_type ] = array(
						'label' => $obj->labels->name,
						'items' => array(),
					);
				}

				$items[ $post->post_type ]['items'][] = $item;

			} else {

				$items[] = $item;

			}
		}

		echo json_encode( array(
			'items' => $items,
			'more' => count( $items ) === $limit,
			'success' => true,
		) );
		wp_die();

	}

Top ↑

Changelog Changelog

Changelog
Version Description
3.32.0 Posts can be queried by post status(es) via the $_POST['post_statuses']. By default only the published posts will be queried.
3.0.0 Introduced.


Top ↑

User Contributed Notes User Contributed Notes

You must log in before being able to contribute a note or feedback.





Permalink: