• Resolved Dekadinious

    (@dekadinious)


    I have a problem with the functions term_exists and wp_insert_term. Say I do something like this:

           $attributeTerm = "X & Y";
            $attribute = "pa_color";
    
            $term = term_exists($attributeTerm, $attribute);
            WP_CLI::log(var_export($term, 1));
    
            if (!$term) {
                $term = wp_insert_term($attributeTerm, $attribute);
    
                if (is_wp_error($term)) {
                    WP_CLI::log(print_r($term, 1));
                }
            }

    If the slug of the term is kind of non-standard, like x-y_895604_895604, then term_exists will return NULL. So the if-block is entered. But then wp_insert_term returns a WP_Error object with the error that the term exists with the same name in that taxonomy.

    Why does this happen? And is it future proof if I use the WP_Error object to get the term_id of the existing term?

    I’d rather the term_exists function work correctly, though.

Viewing 4 replies - 1 through 4 (of 4 total)
  • Thread Starter Dekadinious

    (@dekadinious)

    I guess it is because term_exists only checks for slugs, and if you pass it a name, it uses sanitize_title to convert to slug. wp_insert_term seems to also check for names. That’s kind of inconsistent behavior maybe?

    Moderator bcworkz

    (@bcworkz)

    It checks for name matches as well when there’s no other match from ID or slug. Names should have likewise been sanitized when initially saved, so that shouldn’t be the cause either. The function essentially just returns the result of queries, so any discrepancy would be due to the SQL query, not the WP PHP code running the queries.

    You could try using the Query Monitor plugin to see the queries that were actually run. Try them again in phpMyAdmin to try to find an explanation.

    Thread Starter Dekadinious

    (@dekadinious)

    Thanks!

    It’s the ampersand. It is inserted into the database as “X & Y”. But term_exists does not escape it before checking for existence. It checks for “X & Y”, and that does not exist of course. So this is a problem that will happen with any term that has an ampersand in it, I would think. My tests at least show so.

    This is surely not consistent behavior? One would think that any conversion of characters done in wp_insert_term should also be done when checking for the existence of that term?

    Thread Starter Dekadinious

    (@dekadinious)

    I filed a bug report in trac for this 🙂

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘term_exists returns null, but wp_insert_term can’t insert because it exists’ is closed to new replies.