daro2013
daro2013

Reputation: 71

How to declar a variable using isset() function on Wordpress

I have a block of php codes I put in functions.php on Wordpress website, part of which is as shown below:

add_filter('request', 'my_change_term_request', 1, 1 );

function my_change_term_request($query){

$tax_name = 'ait-items'; // specify you taxonomy name here, it can be also 'category' or 'post_tag'

// Request for child terms differs, we should make an additional check
if( isset( $query['attachment'] ) && $query['attachment'] ) :
    $include_children = true;
    $name = $query['attachment'];
else:
    $include_children = false;
    if(isset($query['name'])){ $name = $query['name']; }
endif;

$term = get_term_by('slug', $name, $tax_name); // get the current term to make sure it exists
if (isset($name) && $term && !is_wp_error($term)): // check it here

    if( $include_children ) {
        unset($query['attachment']);
        $parent = $term->parent;
        while( $parent ) {
            $parent_term = get_term( $parent, $tax_name);
            $name = $parent_term->slug . '/' . $name;
            $parent = $parent_term->parent;
        }
    } else {
        unset($query['name']);
    }

    switch( $tax_name ):
        case 'category':{
            $query['category_name'] = $name; // for categories
            break;
        }
        case 'post_tag':{
            $query['tag'] = $name; // for post tags
            break;
        }
        default:{
            $query[$tax_name] = $name; // for another taxonomies
            break;
        }
    endswitch;

endif;

return $query;

}

This line of codes generates error warning or notice on Wordpress:

$term = get_term_by('slug', $name, $tax_name);

like:

Notice: Undefined variable: name in /wp-content/themes/businessfinder2-child/functions.php on line 595

I have tried to replace the above line with:

$term = get_term_by('slug', if(isset($name)) { echo '$name'; }, $tax_name);

OR:

$term = get_term_by('slug', if(isset($query['name'])) { echo "$name"; }, $tax_name);

None of the above replacements work.

Very appreciate any advice.

Upvotes: 0

Views: 560

Answers (2)

daro2013
daro2013

Reputation: 71

I fixed the issue. In case anyone has experience with similar issue, just declare $name as global variable before the error line like this:

global $name; $term = get_term_by('slug', $name, $tax_name);

or at the beginning of the function.

thanks.

Upvotes: 0

Mohammad Yousefi
Mohammad Yousefi

Reputation: 543

$query is empty in nonsigular pages and it just works in singular page like post and page. Add this line in top of Function to prevent the function call in home page and etc.

if(empty($query)) return $query;

Upvotes: 0

Related Questions