Support

Account

Home Forums Front-end Issues orderby custom field on link click / button

Unread

orderby custom field on link click / button

  • Hey,
    So I’m very new to this but have spent the last few days trying to work it out.

    I have a custom post order for my posts which is the same throughout all category pages which I’d like to keep when people hit those pages. What I’m looking to do is sort the posts by a custom field (price) using a link or button clicked by the client…

    ie – sort by price (low to high)
    – sort by price (high to low)

    I have used this…

    function my_pre_get_posts( $query ) {
    	
    	if( is_admin() ) {
    		
    		return $query;
    		
    	}
    	
    
    	if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'post' ) {
    		
    		$query->set('orderby', 'meta_value_num');	
    		$query->set('meta_key', 'price');	 
    		$query->set('order', 'ASC'); 
    		
    	}
    	
    
    	// return
    	return $query;
    
    }
    
    add_action('pre_get_posts', 'my_pre_get_posts');

    in my functions page which makes all category pages sorted by the custom field (price) on initial load but I can’t figure out how to keep my initial post order and activate the function when someone clicks a button or visits a specific link.

    Ideally when the front end user clicks something the page reloads with all posts in that category re-ordered by my custom field.

    Any ideas?

    Thanks!!

Viewing 1 post (of 1 total)

You must be logged in to reply to this topic.

We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.