WordPress.org

Ready to get started?Download WordPress

Forums

Reorder Category Posts (1 post)

  1. sawyerjw
    Member
    Posted 2 years ago #

    I am trying to reorder posts within a specific category by a precedence value assigned by the blog owner. My plugin creates a custom field the key of which is the name of the selected category. The user can then assign a numeric priority 1-10 which is the value of the custom field. When a visitor clicks on a category to display the posts associated with that specific category, I want the query to order the posts by the priority value (if any). I've been searching the docs, Google, and everywhere else I can think of and have not been able to find anything that works.

    I've added the following function to the pre_get_posts hook:

    // modify query when category page is called
    function process_post_query($query)
    {
    	global $catname;
    
    	if ($query->is_category())
    	{
    		$catname = print_r($query->query_vars['category_name'],true);
    
    		$query->query_vars['meta_key'] = $catname;
    
    		$query->set('orderby','meta_value_num');
    	}
    
    	return $query;
    }

    If I print_r the $query I can see the meta_key value being assigned correctly and the orderby value set as expected, yet the posts are ordered by the default reverse chronological order.

    If I add the following filter to posts_orderby:

    function new_orderby($orderby)
    {
    	global $catname;
    
    	return 'meta_value_num';
    }

    I get the following message in place of the posts:

    "Sorry the category you looking for did not exist or already removed by author"

    I assume I'm missing something simple and fundamental. Any ideas what that might be?

    Thanks in advance.

Topic Closed

This topic has been closed to new replies.

About this Topic