How to set dynamic value when filter by a custom field?

With Content Views Pro, you can set a static value to filter content by custom field easily.
This document will help you to set dynamic value (from URL parameters, current author id, and so on) to filter by custom field. Here is how:

  • please select option for “Field Key”, “Value Type”.
    for “Operator To Compare”, select Equal (=) (or select another option depending on your needs),
    for “Value To Compare”, enter 1 (or enter an actual value, please ensure that value is not blank or empty).
  • then add this code to file functions.php of your active theme:
    // Content Views Pro - set value of custom field dynamically
    add_filter( 'pt_cv_query_ctf_value', 'cvp_theme_query_ctf_dynamic_value', 100, 2 );
    function cvp_theme_query_ctf_dynamic_value( $args, $key ) {
    	global $pt_cv_id;
    	if ( $pt_cv_id === 'VIEW_ID' && $key === 'NAME_OF_CUSTOM_FIELD' ) {
    
    		/* Todo: replace 1 by PHP expression/function to set dynamic value for custom field */
    		$value = 1;
    
    		if ( PT_CV_Functions::setting_value( PT_CV_PREFIX . 'enable-pagination' ) ) {
    			global $pt_cv_id;
    			$trans_key = 'cvp_ctf_value_' . $key . $pt_cv_id;
    			if ( !defined( 'PT_CV_DOING_PAGINATION' ) ) {
    				set_transient( $trans_key, $value, 1 * HOUR_IN_SECONDS );
    			} else {
    				$value = get_transient( $trans_key );
    			}
    		}
    
    		// If value is not empty (0, null, false, empty string/array)
    		if ( !empty( $value ) ) {
    			$args = $value;
    		}
    	}
    
    	return $args;
    }
    

    and replace VIEW_ID with ID of your View, replace NAME_OF_CUSTOM_FIELD with name of the custom field.


If you want to filter the posts that have custom field value is same as custom field value of current post, you can replace $value = 1; in above code with this code:

global $post;
$meta = get_post_meta( $post->ID );
$value = !empty( $meta[ 'NAME_OF_CUSTOM_FIELD' ][ 0 ] ) ? $meta[ 'NAME_OF_CUSTOM_FIELD' ][ 0 ] : 0;

(replace NAME_OF_CUSTOM_FIELD with name of the custom field)

Notice: This task requires coding skill. So please ensure that you know what to do.

Best regards,