• I added a custom ‘checkbox’ field to each of my post with the help of a plugin called [Advanced Custom Field]. The field name is ‘country’ and according to the plugin author,

    **Enter each choice on a new line.For more control, you may specify both a value and label like this:
    red : Red
    blue : Blue**

    My own value and label go like this:

    US: USA

    FR: France

    Now, I want to filter posts based on the ‘country’ field value. So when the URL is like this example.com?country=us, it should display all posts related to USA.

    I added the below code to my functions.php but it’s not working.

    function my_pre_get_posts( $query ) {
    	
    	// do not modify queries in the admin
    	if( is_admin() ) {
    		
    		return $query;
    		
    	}
    	
    	if( isset($query->query_vars['post_type'] && $query->query_vars['post_type'] == 'post')) {
    		
    		// allow the url to alter the query
    		if( isset($_GET['country']) ) {
    			
        		$query->set('meta_key', 'country');
    			$query->set('meta_value', $_GET['country']);
    			
        	} 
    		
    	}
    	
    	
    	// return
    	return $query;
    
        }

    What am I doing wrong?

    • This topic was modified 8 years, 9 months ago by bcworkz. Reason: code fixed
    • This topic was modified 8 years, 9 months ago by bcworkz.
Viewing 8 replies - 1 through 8 (of 8 total)
  • You can try following

    $query->set('meta_query' => array(
                   'key' => 'country',
                   'value' => $_GET[‘country’],
                   'compare' => 'LIKE'
                )
             )

    instead of

    $query->set(‘meta_key’, ‘country’);
    $query->set(‘meta_value’, $_GET[‘country’]);

    This could fix your problem.

    • This reply was modified 8 years, 9 months ago by bcworkz. Reason: code fixed
    Moderator bcworkz

    (@bcworkz)

    If dnyanraja’s solution doesn’t work, on your template, declare global $wp_query;, then echo out $wp_query->request and examine the output, which is the SQL used for your query. It will show why there’s a problem. Post it here if you’re not sure.

    Just to be sure, you have a line like this right?
    add_action('pre_get_posts', 'my_pre_get_posts');

    To prevent conflicts with secondary queries used by some widgets, you should verify the query is for the main query with $query->is_main_query();

    Both you and dnyanraja should demarcate your code with backticks or use the code button, otherwise the code you post is corrupted and not usable.

    Thread Starter Bobozar

    (@skizzy)

    Thanks for your input. Can you help with a code solution. I’m not a PHP developer so I don’t know how to go about writing the code.

    Thread Starter Bobozar

    (@skizzy)

    After trying dnyanraja’s answer, I got the error below:

    Fatal error: Cannot use isset() on the result of an expression (you can use "null !== expression" instead) in C:\wamp64\www\\wp-content\themes\look\functions.php on line 14

    On line 14, I have the below code:

    
    if( isset($query->query_vars['post_type'] && $query->query_vars['post_type'] == 'post')) {
    Moderator bcworkz

    (@bcworkz)

    Ah! We both missed that one, it explains why you’re having trouble with the query. The line should be like this:
    if( isset( $query->query_vars['post_type']) && $query->query_vars['post_type'] == 'post') {

    Setting meta_key and meta_value should be OK unless the default query is modified by another process. In that case dnyanraja’s meta_query alternative may be preferable. If you still have trouble, output the SQL by putting this on the template being used, before or after the Loop:

    global $wp_query;
    echo $wp_query->request;

    Add the <?php ?> tags if your chosen spot is HTML. You can remove it all again after you copy the SQL output.

    You can incorporate the main query check with the admin check:
    if( is_admin() || ! $query->is_main_query()) {

    You probably don’t need this extra check, but it’s good to do just in case.

    Thread Starter Bobozar

    (@skizzy)

    When I adjusted the code and inserted dnyanraja’s meta_query alternative, I got the below error:

    Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW) in C:\wamp64\www\\wp-content\themes\look\functions.php on line 20

    Line 20 reads:

    
    $query->set('meta_query' => array(

    Main code:

    function my_pre_get_posts( $query ) {
    	
    	// do not modify queries in the admin
    	if( is_admin() ) {
    		
    		return $query;
    		
    	}
    	
    	
    	// only modify queries for 'event' post type
    	//if( isset($query->query_vars['post_type'] && $query->query_vars['post_type'] == 'post')) {#
    	if( isset( $query->query_vars['post_type']) && $query->query_vars['post_type'] == 'post') {
    	
    		// allow the url to alter the query
    		if( isset($_GET['country']) ) {
    			
        		$query->set('meta_query' => array(
                   'key' => 'country',
                   'value' => $_GET[‘country’],
                   'compare' => 'LIKE'
                )
             )
    			
        	} 
    	}
    	
    	
    	// return
    	return $query;
    
    }
    
    add_action('pre_get_posts', 'my_pre_get_posts');

    But when I changed it to the below code

    function my_pre_get_posts( $query ) {
    	
    	// do not modify queries in the admin
    	if( is_admin() ) {
    		
    		return $query;
    		
    	}
    	
    	
    	// only modify queries for 'event' post type
    	//if( isset($query->query_vars['post_type'] && $query->query_vars['post_type'] == 'post')) {#
    	if( isset( $query->query_vars['post_type']) && $query->query_vars['post_type'] == 'post') {
    	
    		// allow the url to alter the query
    		if( isset($_GET['country']) ) {
    			
        		$query->set('meta_key', 'country');
    			$query->set('meta_value', $_GET['country']);
    			
        	} 
    			
        	
    	}
    	
    	
    	// return
    	return $query;
    
    }
    
    add_action('pre_get_posts', 'my_pre_get_posts');

    And I visited the url example.com/?country=us

    I got ‘Sorry, Posts you requested could not be found…’

    With this I guess it is not filtering the field.

    Thread Starter Bobozar

    (@skizzy)

    I inserted the below query code in the functions.php function

    global $wp_query;
    echo $wp_query->request;

    And the SQL output goes like this.

    SELECT wpxx_posts.* FROM wpxx_posts WHERE 1=1 AND wpxx_posts.ID = 2647 AND wpxx_posts.post_type = 'page' ORDER BY wpxx_posts.post_date DESC SELECT wpxx_posts.* FROM wpxx_posts WHERE 1=1 AND wpxx_posts.ID = 2647 AND wpxx_posts.post_type = 'page' ORDER BY wpxx_posts.post_date DESC SELECT wpxx_posts.* FROM wpxx_posts WHERE 1=1 AND wpxx_posts.ID = 2647 AND wpxx_posts.post_type = 'page' ORDER BY wpxx_posts.post_date DESC SELECT wpxx_posts.* FROM wpxx_posts WHERE 1=1 AND wpxx_posts.ID = 2647 AND wpxx_posts.post_type = 'page' ORDER BY wpxx_posts.post_date DESC SELECT wpxx_posts.* FROM wpxx_posts WHERE 1=1 AND wpxx_posts.ID = 2647 AND wpxx_posts.post_type = 'page' ORDER BY wpxx_posts.post_date DESC SELECT wpxx_posts.* FROM wpxx_posts WHERE 1=1 AND wpxx_posts.ID = 2647 AND wpxx_posts.post_type = 'page' ORDER BY wpxx_posts.post_date DESC

    The function is:

    function my_pre_get_posts( $query ) {
    	
    	// do not modify queries in the admin
    	if( is_admin() ) {
    		
    		return $query;
    		
    	}
    	
    	
    	// only modify queries for 'event' post type
    	//if( isset($query->query_vars['post_type'] && $query->query_vars['post_type'] == 'post')) {#
    	if( isset( $query->query_vars['post_type']) && $query->query_vars['post_type'] == 'post') {
    	
    		// allow the url to alter the query
    		if( isset($_GET['country']) ) {
    			
        		$query->set('meta_key', 'country');
    			$query->set('meta_value', $_GET['country']);
    			
        	} 
    			
        	
    	}
    	
    	global $wp_query;
        echo $wp_query->request;
    	// return
    	return $query;
    
    }
    
    add_action('pre_get_posts', 'my_pre_get_posts');
    • This reply was modified 8 years, 9 months ago by Bobozar.
    Moderator bcworkz

    (@bcworkz)

    It looks like you have set a static front page in your settings (ID 2647), so the default query is for a single page, not a post listing like we see for a typical blogging site. “Static” is misleading as many so called static front pages are very dynamic. It’s static in the sense a single page is always displayed. That page’s template can dynamically create content, which is likely what is happening on your site.

    You probably need to modify the query on the front page template to use the country parameter and restrict the query based on it. Documentation for queries like this are in the Codex. You need to alter the query arguments for this query to include the meta key and meta value arguments. (or meta_query if you want to go that way) It’s the same concept as with pre_get_posts, but you go about it slightly differently.

    I’m going to be away from all things internet for a few days. When you get no response from me in the next few days, that’s why. I’m not ignoring you, I’ll be happy to answer any further questions when I return Friday. Until then, good luck!

Viewing 8 replies - 1 through 8 (of 8 total)

The topic ‘Get Custom Field Value With URL Parameter’ is closed to new replies.