WordCount Filter using Compare meta query - mdhemalakhand1999/WordPressPluginDevelopment GitHub Wiki


/**
 * Let's create a select form for WordCount filter
 */
function coldemo_wc_filter() {
	if ( isset( $_GET['post_type'] ) && $_GET['post_type'] != 'post' ) { //display only on posts page
		return;
	}


	$filter_value = isset( $_GET['WCFILTER'] ) ? $_GET['WCFILTER'] : '';
	$values       = array(
		'0' => __( 'Word Count', 'column_demo' ),
		'1' => __( 'Above 400', 'column_demo' ),
		'2' => __( '200 to 400', 'column_demo' ),
		'3' => __( 'Below 200', 'column_demo' ),
	);
	?>
    <select name="WCFILTER">
		<?php
		foreach ( $values as $key => $value ) {
			printf( "<option value='%s' %s>%s</option>", $key,
				$key == $filter_value ? "selected = 'selected'" : '',
				$value
			);
		}
		?>
    </select>
	<?php
}

add_action( 'restrict_manage_posts', 'coldemo_wc_filter' );

/**
 * Let's add functionality for sorting wordcount
 */
function coldemo_wc_filter_data( $wpquery ) {
	if ( ! is_admin() ) {
		return;
	}


	$filter_value = isset( $_GET['WCFILTER'] ) ? $_GET['WCFILTER'] : '';

	if ( '1' == $filter_value ) {
		$wpquery->set( 'meta_query', array(
			array(
				'key'     => 'wordn',
				'value'   => 400,
				'compare' => '>=',
				'type'    => 'NUMERIC'
			)
		) );
	} else if ( '2' == $filter_value ) {
		$wpquery->set( 'meta_query', array(
			array(
				'key'     => 'wordn',
				'value'   => array(200,400),
				'compare' => 'BETWEEN',
				'type'    => 'NUMERIC'
			)
		) );
	} else if ( '3' == $filter_value ) {
		$wpquery->set( 'meta_query', array(
			array(
				'key'     => 'wordn',
				'value'   => 200,
				'compare' => '<=',
				'type'    => 'NUMERIC'
			)
		) );
	}


}

add_action( 'pre_get_posts', 'coldemo_wc_filter_data' );
⚠️ **GitHub.com Fallback** ⚠️