AnsPress_Post_Table_Hooks::posts_clauses( array $sql, object $instance )

Description #

Modify SQL query.

Parameters #

  • $sql
    array (Required) Sql claues.
  • $instance
    object (Required) WP_Query instance.

Source #

File: admin/class-list-table-hooks.php

	public static function posts_clauses( $sql, $instance ) {
		global $pagenow, $wpdb;
		$vars = $instance->query_vars;

		if ( ! in_array( $vars['post_type'], array( 'question', 'answer' ), true ) ) {
			return $sql;
		}

		$sql['join']   = $sql['join'] . " LEFT JOIN {$wpdb->ap_qameta} qameta ON qameta.post_id = {$wpdb->posts}.ID";
		$sql['fields'] = $sql['fields'] . ', qameta.*, qameta.votes_up - qameta.votes_down AS votes_net';

		// Show only flagged posts.
		if ( 'edit.php' === $pagenow && ap_sanitize_unslash( 'flagged', 'p' ) ) {
			$sql['where']   = $sql['where'] . ' AND qameta.flags > 0';
			$sql['orderby'] = ' qameta.flags DESC, ' . $sql['orderby'];
		}

		$orderby = ap_sanitize_unslash( 'orderby', 'p' );
		$order   = ap_sanitize_unslash( 'order', 'p' ) === 'asc' ? 'asc' : 'desc';

		if ( 'flags' === $orderby ) {
			// Sort by flags.
			$sql['orderby'] = " qameta.flags {$order}";
		} elseif ( 'answers' === $orderby ) {
			// Sort by answers.
			$sql['orderby'] = " qameta.answers {$order}";
		} elseif ( 'votes' === $orderby ) {
			// Sort by answers.
			$sql['orderby'] = " votes_net {$order}";
		}

		return $sql;
	}

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