Support

Account

Home Forums Backend Issues (wp-admin) control post order with options page

Solving

control post order with options page

  • Hi All
    I would like to control the order of the posts in the archive page.
    Have a drop down with:
    –order by Date
    –order by Title
    and a radio button for:
    –ASC and
    –DESC

    This should work for posts and custom post type separately, in the future, maybe based on a category.
    The control would be within an ‘Options’ page.

    Could you lead me in the right direction, has anyone done this feature before?

    Thanks!
    Dan

  • I do this for posts_per_page for different post types so that clients can determine how many posts to show on archive pages.

    You need to create a pre_get_posts query and check settings and alter the query based on the settings.

    Here is an example filter I created for a recent project that does this

    
    function pre_get_posts_locations($query) {
      
      // not in admin or if not main query
      if (is_admin() || !$query->is_main_query()) {
        return;
      }
      
      // only queries for location post type
      if (!isset($query->query_vars) ||
          !isset($query->query_vars['post_type']) ||
          $query->query_vars['post_type'] != 'location') {
        return;
      }
      
      // not for single
      if (is_single()) {
        return;
      }
      
      // set locations per page
      $posts_per_page = get_field('locations_per_page', 'options');
      if ($posts_per_page === NULL || $posts_per_page === false) {
        // if never set show default of 10
        $posts_per_page = 10;
      }
      if (!$posts_per_page) {
        // if set to 0 show all
        $posts_per_page = -1;
      }
      $query->set('posts_per_page', $posts_per_page);
      
      // show only active locations
      $meta_query = array(
        array(
          'key' => 'active',
          'value' => 1
        )
      );
      $query->set('meta_query', $meta_query);
      
      $orderby = array(
        'menu_order' => 'ASC',
        'title' => 'ASC'
      );
      $query->set('orderby', $orderby);
      
      
    }
    

    The orderby part of the query at the end could also be set up to use options settings if needed.

  • Thank you John, I will try that out.

    Dan

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.