• Is get_term_by actually a correct function ?

    E.g.:

    get_term_by('name','book','category')

    works as long as you only have one category in there with the name book, but if you have \bla\book and \def\dof\book also, it will just be random which one it will output.

    So instead of the get_term_by query:

    $term = $wpdb->get_row( $wpdb->prepare( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE $_field = %s", $value ) . " $tax_clause LIMIT 1" );

    Maybe it should check if there are multiple returned then also return multiple in all cases, I think LIMIT 1 should be removed, otherwise you can never check if multiple exist.

    $term = $wpdb->get_row( $wpdb->prepare( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE $_field = %s", $value ) . " $tax_clause " );

    So you cant use ‘name’, otherwise you would need to do something like:

    $categorychildren = get_term_children(config::getRootTermId(), 'category');
    			foreach($categorychildren as $wp_category_id) {
    				$cat_object = get_term($wp_category_id, 'category');
    				if ($cat_object->name == $whatwelookfor) {
    					// .. do the rest
    				}
    			}
Viewing 2 replies - 1 through 2 (of 2 total)
  • Not sure what your question is here? It sounds like you’ve already answered yourself (?).

    Yes, get_term_by is a valid function.
    https://codex.wordpress.org/Function_Reference/get_term_by

    For the record, it’s never a good idea to give two (or more) categories the same name, but of course you can – however WP will save them with different ID numbers and slugs, so as long as you’re querying on either the ID or slug you’ll be fine.

    Thread Starter cogmios

    (@cogmios)

    What I mean to say is:

    I think that get_term_by should return WP_ERROR if multiple are found.

    I understand that you can query on unique properties but get_term_by lets you also query on non-unique properties and then the outcome will be random.

    In a taxonomy names are not unique. So if you want to get a term out of a taxonomy it makes no sense to limit it to 1 since the outcome will be random.

    \legal\public\contract
    \finance\leasing\contract

    If a developer uses accidently get_term_by without having the taxonomy content yet, it could lead to bugs later on when the users enter the actual taxonomy and only then the realization comes. So the function should protect the developer from making mistakes.

    It should return an error if multiple are found Or return multiple OR always require the full hierarchical path, but not just return a random one.

    update: submitted propsal in trac: https://core.trac.wordpress.org/ticket/36878#ticket

    please challenge/enlighten

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘get_term_by for multiple cats with same name’ is closed to new replies.