Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine multiple custom user taxonomy in single url

I have created custom user taxonomy for user and its working good for single taxonomy.

From Bellow reference guide i have created custom user taxonomy.

Reference guide:- http://justintadlock.com/archives/2011/10/20/custom-user-taxonomies-in-wordpress

Bellow is structure of taxonomy

(registered taxonomy)  profession

                              Dietitian (under the profession )



(registered taxonomy) city
                         NewYork(under the city)

my slug name name expert

Here i want to display filter result which user is Dietitian in NewYork city.so it will display all user which have selected above option in profile.

Now i want the url something like www.test.com/expert/dietitian/newyork with user which have selected Dietitian , NewYork in user profile. And is there any solution to combine Dietitian,NewYork

The url with single terms works like:- www.test.com/expert/dietitian/

like image 973
Sanjay Nakate Avatar asked Dec 18 '15 08:12

Sanjay Nakate


2 Answers

I am assuming that you have spend a great deal of time on the tutorial of justintadlock, so I will get involved only with the parts of it that are needed for the multiple taxonomy filtering and display on the front-end.

Before your read the long text, you can have a taste at http://playground.georgemanousarides.com/

So, first thing's first. The logical base is the same for both SINGLE TAXONOMY and MULTIPLE TAXONOMIES. After having registered the taxonomies and their terms and have done all the work needed wp-admin wise, we will need:

A) A page (lets call it TAX-QUERY PAGE) in which visitors can select the taxonomy query.

B) Another page (lets call it TAX-RESULTS PAGE) in which the results of TAX-QUERY PAGE will be displayed.

Let's dive in


SINGLE TAXONOMY

TAX-QUERY PAGE

After following the tutorial, the page that you display the taxonomies links should look, on its primal form, like this:

single taxonomy tax-query page

Visitors "Select" which taxonomy they want to see by simply clicking on the links provided.

Note that:

A) The links for:

  1. Proffession will be like: www.example.com/user/profession/developer/
  2. City will be like: www.example.com/user/city/gotham/

B) The slugs "user/city" and "user/profession" are defined at the function: my_register_user_taxonomy >> register_taxonomy >> rewrite >> slug

TAX-RESULTS PAGE

Clicking on the links mentioned above takes you to a page ( which needs to be defined by you of course ) that displays all the users under the same taxonomy-term.

This is achieved by creating custom taxonomy templates.

You can create the taxonomy-profession-developer.php file to handle a single taxonomy and term, or the taxonomy-profession.php to handle a single taxonomy and all its' terms, or the taxonomy.php for all taxonomies and their terms.

In my opinion, if you don't want your server to be flooded with template files which are manually created by you, you should use the taxonomy.php and make a general teplate for all taxonomies which descriminates the results you want to display automatically.

Note that:

A) To itterate through users and fetch only those under the desired taxonomy-term, a custom query is needed ( in the taxonomy.php file ), as mentioned and explained in the tutorial.

B) Permalinks should be on Post Name option from the wp-admin >> settings >> permalinks so that wordpress can find your taxonomies, fetch the file taxonomy.php and provide usefull info about the selected taxonomy that can be used in the taxonomy.php file.


MULTIPLE TAXONOMIES

TAX-QUERY PAGE

We need to create a page where visitors will select terms from the custom taxonomies. This page will provide the TAX-RESULTS PAGE ( taxonomy.php ) with the needed terms through a link (as get variables**) so as to make a query.

**In order to have pretty permalinks in the TAX-RESULTS PAGE we need to add the following rewrite function (found it here) to the function.php, and refresh the permalinks in wp-admin:

function eg_add_rewrite_rules() {
  global $wp_rewrite;
  $new_rules = array(
      'user/(profession|city)/(.+?)/(profession|city)/(.+?)/?$' => 'index.php?post_type=eg_event&' . $wp_rewrite->preg_index(1) . '=' . $wp_rewrite->preg_index(2) . '&' . $wp_rewrite->preg_index(3) . '=' . $wp_rewrite->preg_index(4),
      'user/(profession|city)/(.+)/?$' => 'index.php?post_type=eg_event&' . $wp_rewrite->preg_index(1) . '=' . $wp_rewrite->preg_index(2)
  );
  $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}
add_action( 'generate_rewrite_rules', 'eg_add_rewrite_rules' );

Note that

If you register more taxonomies the "profession|city" in the function should become "profession|city|tax1|tax2|tax3".

So the TAX-QUERY PAGE will be:

HTML

<div id="taxonomies">
    <h1>Find your professional</h1>
    <form>
        <?php if ( $taxonomies = get_object_taxonomies( 'user' ) ) : //get all taxonomies under the object_type "user" ( The second parameter given to the function my_register_user_taxonomy of the tutorial )
            foreach ( $taxonomies as $taxonomy ) : ?>
                <p>
                    <ul>
                        <fieldset id="<?php echo esc_attr( $taxonomy ); ?>"> <!-- group the form by taxonomies -->
                            <legend><h2>Choose <?php echo $taxonomy; ?></h2></legend>
                            <?php if ( $terms = get_terms( $taxonomy ) ) : //get taxonomy's terms
                                foreach ( $terms as $term ) : ?>
                                    <li><input type="checkbox" value="<?php echo esc_attr( $term -> slug ); ?>"> <?php echo $term -> name; ?></li>
                                <?php   endforeach;
                            endif; ?>
                        </fieldset>
                    </ul>
                </p>
            <?php   endforeach;
        endif; ?>
    </form>
    <a id="multiTaxSubmit" href="<?php echo esc_attr( get_home_url() . '/user' ); ?>">SUBMIT</a> <!-- this link is processed by jQuery to provide the taxonomy.php with the proper values. The href attribute is the base url needed by the taxonomy.php -->
</div>

JQUERY ( Can be put in an external file )

$( document ).ready( function() {
    $( '#multiTaxSubmit' ).click( function ( event ){
        event.preventDefault(); //prevent default link url from loading
        var taxQuerySubmit = $( this ),
                hasChecked = 0;
                querySlug = taxQuerySubmit.attr( 'href' ); //get multitax url base from link href attr
        $( '#taxonomies fieldset' ).each( function() { //iterate each taxonomy
            var checkedTerms = $( this ).find( 'input:checked' ),
                    checkedLength = checkedTerms.length; //how many terms has the user selected
            if ( checkedLength ) {
                hasChecked += checkedLength;
                querySlug += '/' + $( this ).attr( 'id' ) + '/'; //add taxonomy slug to query url
                checkedTerms.each( function( index, value ) {
                    var comma = ( index == checkedLength-1 ? '' : ',' );
                    querySlug += $( this ).val() + comma;
                } );
            }
        } );
        if ( hasChecked ) {
            window.location = querySlug;
        } else {
            alert( 'Please enter some criteria.' );
        }
    } );
} );

TAX-RESULTS PAGE ( taxonomy.php )

<?php
    $USERS_BY_TAX = array();
    if ( $taxonomies = get_object_taxonomies( 'user' ) ) { //get all taxonomies under the object_type "user" ( The second parameter given to the function my_register_user_taxonomy of the tutorial )
        foreach ( $taxonomies as $tax_key => $taxonomy ) {
            eval( '$check = $' . $taxonomy . ';' ); // Check if the taxonomy exists in the url. eval outputs $check = $profession, $check = $city etc.
            if ( !$check ){
                unset( $taxonomies[ $tax_key ] );
                continue;
            }
            eval( '$term_names = explode( ",", $' . $taxonomy . ' );' ); // get terms array from $$taxonomy which gives $profession,$city, the values of which are given through the url as such: $profession="designer,developer"
            $USERS_BY_TAX[ $taxonomy ] = array();
            foreach ( $term_names as $term_name ) {
                $term_obj = get_term_by( 'name', $term_name, $taxonomy ); //get term object for each given term
                $users_in_term = get_objects_in_term( $term_obj -> term_id, $taxonomy ); // find users with term
                if ( !empty( $users_in_term ) ) {
                    $USERS_BY_TAX[ $taxonomy ] = $USERS_BY_TAX[ $taxonomy ] + array_fill_keys( $users_in_term, $term_name ) ;
                }
            }
        }
    }
    /* $USERS_BY_TAX array has all the users for each taxonomy but we only need those who exist in all taxonomies */
    if ( $taxonomies ) {
        $RESULTS = $USERS_BY_TAX; // keep the initiate array intact
        $matched = array_pop( $USERS_BY_TAX ); // first array to compare
        $TAXS = $taxonomies;
        array_pop( $taxonomies );
        if ( !empty( $USERS_BY_TAX ) ) {
            foreach ( $taxonomies as $taxonomy ) {
                if ( !empty( $USERS_BY_TAX ) ) $matched = array_intersect_key( $matched, $USERS_BY_TAX[ $taxonomy ] );
            }
        }
    }
?>

/* DISPLAY */
<?php if ( $matched ) :
    foreach ( array_keys( $matched ) as $user_id ): ?>

        <div class="user-entry">
            <?php echo get_avatar( get_the_author_meta( 'email', $user_id ), '96' ); ?>
            <h2><?php the_author_meta( 'display_name', $user_id ); ?></h2>
            <?php if ( in_array( 'profession', $TAXS ) ) : ?><h3>Profession: <?php echo $RESULTS[ 'profession' ][ $user_id ]; ?></h3><?php endif;?>
            <?php if ( in_array( 'city', $TAXS ) ) : ?><h3>City: <?php echo $RESULTS[ 'city' ][ $user_id ]; ?></h3><?php endif;?>
            <?php echo wpautop( get_the_author_meta( 'description', $user_id ) ); ?>
        </div>

    <?php endforeach;
else: ?>
        <div class="user-entry">
            <h2>We are sorry. No results match your criteria.</h2>
            <h3>Please <a href="javascript:history.back()">go back</a> and search again!</h3>
        </div>
<?php endif; ?>
like image 132
gmanousaridis Avatar answered Nov 11 '22 12:11

gmanousaridis


This rewrite rule should work (assuming "profession" and "city" are the taxonomy registered names):

Code:

function custom_rewrite_rules() {
    add_rewrite_rule('^profession/(.*)/city/(.*)?', 'index.php?profession=$matches[1]&city=$matches[2]', 'top');
}
add_action('init', 'custom_rewrite_rules');

Remember to flush the rewirte rules after saving this code in your site.

URL : http://yourdomain.com/profession/dietitian/city/newyork/

like image 40
Dr.Tricker Avatar answered Nov 11 '22 14:11

Dr.Tricker