• Hello,
    my website is about people and my urls look something like this:

    mydomain.com/age/45/
    mydomain.com/height/176cm/
    mydomain.com/birthplace/germany/hamburg/

    Age, height and birthplace are custom taxonomies, and 45, 176cm and germany/hamburg are taxonomy terms.

    Now I use ‘posts_where’ to split these results into men and women by using a custom field “gender” from a custom table “persons”:

    add_filter('posts_where', 'gender');
    function gender( $where ) {
    if (is_tax()) {
    global $wpdb;
    if (isset($_GET['g'])) {
    if ($_GET['g'] === 'women') {
    $where .= " AND gender = 'She' ";
    }
    elseif ($_GET['g'] === 'men') {
    $where .= " AND gender = 'He' ";
    }
    }
    }
    return $where;
    }

    This works and the URLs look like this:
    mydomain.com/age/45/?g=women and mydomain.com/age/45/?g=men

    But I would like to use pretty permalinks like this:
    mydomain.com/age/45/women/ and mydomain.com/age/45/men/

    I found some examples with add_rewrite_rule, but it doesn’t seem to work with ‘posts_where’, I always get a message “page not found”. Maybe it’s because I work with custom fields in a custom table?

    I would be happy, if someone could help me!

    Thank you in advance!
    Andreas

Viewing 3 replies - 1 through 3 (of 3 total)
  • Hi Andreas, have you thought about finding a plugin that could handle the rewrite rules for your permalinks? There are a variety that might help you with these mappings/rules. This query could get you started: https://www.ads-software.com/plugins/search/custom+permalinks/

    Also, there are some good docs on the rewrite function: https://developer.www.ads-software.com/reference/classes/wp_rewrite/rewrite_rules/

    Have you tried any of those plugins?

    Thread Starter Andreas 2013

    (@andreas-2013)

    Hi Dan,

    I solved the problem manually with this code:

    add_filter('posts_where', 'gender');
    function geschlecht( $where ) {
    if (is_tax()) {
    $url = $_SERVER['REQUEST_URI'];
    global $wpdb;
    if (preg_match ('#women#', $_SERVER['REQUEST_URI'])) {
    $where .= " AND gender= 'She' ";
    }
    elseif (preg_match ('#men#', $_SERVER['REQUEST_URI'])) {
    $where .= " AND geschlecht = 'He' ";
    }
    }
    return $where;
    }
    
    add_action( 'init', 'test' );
    function test() { 
    add_rewrite_rule('height/([^/]+)/women/?$', 'index.php?height=$matches[1]&g=women', 'top');
    add_rewrite_rule('height/([^/]+)/men/?$', 'index.php?height=$matches[1]&g=men', 'top');
    
    }

    Now everything is fine! Thanks for your time ??

    • This reply was modified 1 year, 7 months ago by Andreas 2013.

    That is amazing! Fantastic – so glad you got it to where you wanted!

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Custom field in query string: change to pretty permalink’ is closed to new replies.