0

There is a nonhierarchical custom post type "news".

/news/
/news/page/2/
/news/post_slug/

Each post has custom field "views". When someone opens post, field's value increased by one.

Would like to sort posts by this custom field, by its value.

/news/
/news/views/ = /news/?sort=views (get posts with custom field "views" and sort asc)
/news/views/page/2/ = /news/?sort=views&page=2 (similar to previous, next page)
/news/post_slug/

Got working /news/?sort=views, but this link is not human-like.

It should be transformed to /news/views/ and be able to handle pagination.

How can we do this?

1 Answer 1

1

You need to look at add_rewrite_tag() and add_rewrite_rule()

Also read this and this topics. They are very close to you issue.

After you setup rewrite rule don't forget to flush rules

add_action( 'wp_loaded','my_flush_rules' ); // flush_rules() if our rules are not yet included
function my_flush_rules(){
    $rules = get_option( 'rewrite_rules' );
    $pattern = 'news/([^/]+)?'; // the same pattern that was used in add_rewrite_rule
    if ( !isset( $rules[$pattern] ) ) {
        global $wp_rewrite;
        $wp_rewrite->flush_rules();
    }
}
3
  • this code doesnt work Nov 12, 2011 at 12:53
  • did you setup add_rewrite_tag() and add_rewrite_rule()?
    – Alexey
    Nov 12, 2011 at 17:33
  • I don't know how Nov 12, 2011 at 20:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.