BP_REST_Topics_Endpoint::get_items( WP_REST_Request $request )

Retrieve Topics.

Description

Parameters

$request

(WP_REST_Request) (Required) Full details about the request. - from bbp_has_topics().

Return

(WP_REST_Response) | WP_Error

Source

File: bp-forums/classes/class-bp-rest-topics-endpoint.php

	public function get_items( $request ) {

		global $wpdb;

		$args = array(
			'post_parent'    => ( ! empty( $request['parent'] ) ? $request['parent'] : '' ),
			'orderby'        => ( ! empty( $request['orderby'] ) ? $request['orderby'] : 'meta_value' ),
			'order'          => ( ! empty( $request['order'] ) ? $request['order'] : 'desc' ),
			'paged'          => ( ! empty( $request['page'] ) ? $request['page'] : '' ),
			'posts_per_page' => ( ! empty( $request['per_page'] ) ? $request['per_page'] : bbp_get_topics_per_page() ),
		);

		if ( ! empty( $request['status'] ) ) {
			$args['post_status'] = implode( ' ', $request['status'] );
		}

		if ( ! empty( $request['search'] ) ) {
			$args['s'] = $this->bbp_sanitize_search_request( $request['search'] );
		}

		if ( ! empty( $request['author'] ) ) {
			$args['author'] = $request['author'];
		}

		if ( ! empty( $request['author_exclude'] ) ) {
			$args['author__not_in'] = $request['author_exclude'];
		}

		if ( ! empty( $request['exclude'] ) ) {
			$args['post__not_in'] = $request['exclude'];
		}

		if ( ! empty( $request['include'] ) ) {
			$args['post__in'] = $request['include'];
		}

		if ( ! empty( $request['offset'] ) ) {
			$args['offset'] = $request['offset'];
		}
		$default_show_stickies = false;

		if (
			! empty( $args['post_parent'] )
			&& 'forum' === get_post_type( $args['post_parent'] )
			&& empty( $request['search'] )
		) {
			$default_show_stickies = true;
		}

		if (
			! empty( $args['orderby'] )
			&& is_array( $args['orderby'] )
		) {
			if ( in_array( 'popular', $args['orderby'], true ) ) {
				$args['orderby']  = 'meta_value_num';
				$args['meta_key'] = '_bbp_reply_count'; // phpcs:ignore
			} elseif ( in_array( 'activity', $args['orderby'], true ) ) {
				$args['orderby']  = 'meta_value';
				$args['meta_key'] = '_bbp_last_active_time'; // phpcs:ignore
			}
		}

		if ( is_array( $args['orderby'] ) ) {
			$args['orderby'] = implode( ' ', $args['orderby'] );
		}

		/**
		 * Filter the query arguments for the request.
		 *
		 * @param array           $args    Key value array of query var to query value.
		 * @param WP_REST_Request $request The request sent to the API.
		 *
		 * @since 0.1.0
		 */
		$args = apply_filters( 'bp_rest_topics_get_items_query_args', $args, $request );

		$default = array(
			'post_type'                => bbp_get_topic_post_type(), // Narrow query down to bbPress topics.
			'show_stickies'            => $default_show_stickies,    // Ignore sticky topics?
			'max_num_pages'            => false,                     // Maximum number of pages to show.

			// Conditionally prime the cache for related posts.
			'update_post_family_cache' => true,
		);

		if ( ! empty( $args['post_parent'] ) ) {
			// phpcs:ignore
			$default['meta_key'] = '_bbp_last_active_time';
		}

		// What are the default allowed statuses (based on user caps).
		if ( bbp_get_view_all( 'edit_others_topics' ) ) {

			// Default view=all statuses.
			$post_statuses = array_keys( bbp_get_topic_statuses() );

			// Add support for private status.
			if ( current_user_can( 'read_private_topics' ) ) {
				$post_statuses[] = bbp_get_private_status_id();
			}

			// Join post statuses together.
			$default['post_status'] = $post_statuses;

			// Lean on the 'perm' query var value of 'readable' to provide statuses.
		} else {
			$default['perm'] = 'readable';
		}

		$tag = sanitize_title( $request->get_param( 'tag' ) );

		if ( bbp_allow_topic_tags() && ! empty( $tag ) ) {
			$default['term']     = bbp_get_topic_tag_slug( $tag );
			$default['taxonomy'] = bbp_get_topic_tag_tax_id();
		}

		$bbp_t = bbp_parse_args( $args, $default, 'has_topics' );

		if ( isset( $request['subscriptions'] ) && ! empty( $request['subscriptions'] ) ) {
			$user_id = (int) (
			( isset( $args['author'] ) && ! empty( $args['author'] ) )
				? $args['author']
				: bbp_get_current_user_id()
			);

			$subscriptions = bbp_get_user_subscribed_topic_ids( $user_id );
			if ( ! empty( $subscriptions ) ) {
				$bbp_t['post__in'] = $subscriptions;
				if ( isset( $args['author'] ) ) {
					unset( $bbp_t['author'] );
				}
			} else {
				$bbp_t = array();
			}
		} elseif ( isset( $request['favorites'] ) && ! empty( $request['favorites'] ) ) {
			$user_id = (int) (
			( isset( $args['author'] ) && ! empty( $args['author'] ) )
				? $args['author']
				: bbp_get_current_user_id()
			);

			$favorites = bbp_get_user_favorites_topic_ids( $user_id );
			if ( ! empty( $favorites ) ) {
				$bbp_t['post__in'] = $favorites;
				if ( isset( $args['author'] ) ) {
					unset( $bbp_t['author'] );
				}
			} else {
				$bbp_t = array();
			}
		}

		// Run the query.
		$topics_query = new WP_Query( $bbp_t );

		/** Stickies */
		// Put sticky posts at the top of the posts array.
		if ( ! empty( $bbp_t['show_stickies'] ) && $bbp_t['paged'] <= 1 ) {

			// Strip the super stickies from topic query.
			// bp-forums/groups.php L791.
			if (
				! empty( $bbp_t['post_parent'] )
				&& 'forum' === get_post_type( $bbp_t['post_parent'] )
			) {
				$group_ids = bbp_get_forum_group_ids( $bbp_t['post_parent'] );
				if ( ! empty( $group_ids ) ) {
					add_filter( 'bbp_get_super_stickies', array( $this, 'no_super_stickies' ), 10, 1 );
				}
			}

			// Get super stickies and stickies in this forum.
			$stickies = bbp_get_super_stickies();

			// Strip the super stickies from topic query.
			if (
				! empty( $bbp_t['post_parent'] )
				&& 'forum' === get_post_type( $bbp_t['post_parent'] )
			) {
				$group_ids = bbp_get_forum_group_ids( $bbp_t['post_parent'] );
				if ( ! empty( $group_ids ) ) {
					remove_filter( 'bbp_get_super_stickies', array( $this, 'no_super_stickies' ), 10, 1 );
				}
			}

			// Get stickies for current forum.
			if ( ! empty( $bbp_t['post_parent'] ) ) {
				$stickies = array_merge( $stickies, bbp_get_stickies( $bbp_t['post_parent'] ) );
			}

			// Remove any duplicate stickies.
			$stickies = array_unique( $stickies );

			// We have stickies.
			if ( is_array( $stickies ) && ! empty( $stickies ) ) {

				// Start the offset at -1 so first sticky is at correct 0 offset.
				$sticky_offset = - 1;

				// Loop over topics and relocate stickies to the front.
				foreach ( $stickies as $sticky_index => $sticky_id ) {

					// Get the post offset from the posts array.
					$post_offsets = wp_filter_object_list( $topics_query->posts, array( 'ID' => $sticky_id ), 'OR', 'ID' );

					// Continue if no post offsets.
					if ( empty( $post_offsets ) ) {
						continue;
					}

					// Loop over posts in current query and splice them into position.
					foreach ( array_keys( $post_offsets ) as $post_offset ) {
						$sticky_offset ++;

						$sticky = $topics_query->posts[ $post_offset ];

						// Remove sticky from current position.
						array_splice( $topics_query->posts, $post_offset, 1 );

						// Move to front, after other stickies.
						array_splice( $topics_query->posts, $sticky_offset, 0, array( $sticky ) );

						// Cleanup.
						unset( $stickies[ $sticky_index ] );
						unset( $sticky );
					}

					// Cleanup.
					unset( $post_offsets );
				}

				// Cleanup.
				unset( $sticky_offset );

				// If any posts have been excluded specifically, Ignore those that are sticky.
				if ( ! empty( $stickies ) && ! empty( $bbp_t['post__not_in'] ) ) {
					$stickies = array_diff( $stickies, $bbp_t['post__not_in'] );
				}

				// Fetch sticky posts that weren't in the query results.
				if ( ! empty( $stickies ) ) {

					// Query to use in get_posts to get sticky posts.
					$sticky_query = array(
						'post_type'   => bbp_get_topic_post_type(),
						'post_parent' => 'any',
						'meta_key'    => '_bbp_last_active_time', // phpcs:ignore
						'orderby'     => 'meta_value',
						'order'       => 'DESC',
						'include'     => $stickies,
					);

					// Cleanup.
					unset( $stickies );

					// Conditionally exclude private/hidden forum ID's.
					$exclude_forum_ids = bbp_exclude_forum_ids( 'array' );
					if ( ! empty( $exclude_forum_ids ) ) {
						$sticky_query['post_parent__not_in'] = $exclude_forum_ids;
					}

					// What are the default allowed statuses (based on user caps).
					if ( bbp_get_view_all( 'edit_others_topics' ) ) {
						$sticky_query['post_status'] = $bbp_t['post_status'];

						// Lean on the 'perm' query var value of 'readable' to provide statuses.
					} else {
						$sticky_query['post_status'] = $bbp_t['perm'];
					}

					// Get all stickies.
					$sticky_posts = get_posts( $sticky_query );

					if ( ! empty( $sticky_posts ) ) {

						// Get a count of the visible stickies.
						$sticky_count = count( $sticky_posts );

						// Merge the stickies topics with the query topics.
						$topics_query->posts = array_merge( $sticky_posts, $topics_query->posts );

						// Adjust loop and counts for new sticky positions.
						$topics_query->found_posts = (int) $topics_query->found_posts + (int) $sticky_count;
						$topics_query->post_count  = (int) $topics_query->post_count + (int) $sticky_count;

						// Cleanup.
						unset( $sticky_posts );
					}
				}
			}
		}

		// If no limit to posts per page, set it to the current post_count.
		if ( - 1 === $bbp_t['posts_per_page'] ) {
			$topics_query->posts_per_page = $topics_query->post_count;
		}
		/** --Stickies */

		$topics = ( ! empty( $topics_query->posts ) ? $topics_query->posts : array() );

		$retval = array();
		foreach ( $topics as $topic ) {
			$retval[] = $this->prepare_response_for_collection(
				$this->prepare_item_for_response( $topic, $request )
			);
		}

		$response = rest_ensure_response( $retval );
		$response = bp_rest_response_add_total_headers( $response, $topics_query->found_posts, $args['posts_per_page'] );

		/**
		 * Fires after a list of topics is fetched via the REST API.
		 *
		 * @param array            $topics   Fetched Topics.
		 * @param WP_REST_Response $response The response data.
		 * @param WP_REST_Request  $request  The request sent to the API.
		 *
		 * @since 0.1.0
		 */
		do_action( 'bp_rest_topics_get_items', $topics, $response, $request );

		return $response;
	}

Changelog

Changelog
Version Description
0.1.0 Introduced.

Questions?

We're always happy to help with code or other questions you might have! Search our developer docs, contact support, or connect with our sales team.