get_term_children returns WP_Error for custom taxonomy

What I’m working on is a ajax based dropdown option form which returns child terms based on the option selected.

When the option is selected, a function is fired using onchange, where the script grabs the term_id and taxonomy of the selected option, and sends both of those to the server.

Read More

The server side script I created accepts $_POST, I have verified that the variables are properly assigned by echoing them back to the client and checking the console logs.

<?php
//Include wordpress
require_once( 'wp-config.php' );
require_once( 'wp-includes/wp-db.php' );
$wpdb = new wpdb( DB_USER , DB_PASSWORD , DB_NAME , DB_HOST );

if (isset($_POST)){
    $taxID = $_POST[id];
    $taxType = $_POST[tx];
}
else {
    echo "Error: invalid data recieved. Please contact the site administrator.";
    die();
}

$termchildren = get_term_children( $taxID, $taxType );

echo '<ul>';
foreach ( $termchildren as $child ) {
    $term = get_term_by( 'id', $child, $taxType );
    echo '<li><a href="' . get_term_link( $term->name, $taxType ) . '">' . $term->name . '</a></li>';
}
echo '</ul>';
die();
?>

The goal of this script is to return some html that I can insert into another element.
– The ID of the element causing issues is 4, which contains a child with ID of 15
– The taxonomy of the element is classifieds_categories
– Passing these values manually does not work either.
– When I echo the li a href I get this error:
Catchable fatal error: Object of class WP_Error could not be converted to string in ...

Does anyone have any suggestions? Because quite frankly I’m about to throw my laptop towards the nearest window at this point.

Related posts

2 comments

  1. Since get_term_link() will return a WP_Error object if the term does not exist, you could try:

    $termchildren = get_term_children( $taxID, $taxType );
    
    echo '<ul>';
    foreach ( $termchildren as $child ) {
        $term = get_term_by( 'id', $child, $taxType );
    
        $term_link = get_term_link( $term->name, $taxType );
    
        if( ! is_wp_error( $term_link ) )    
             echo '<li><a href="' . $term_link . '">' . $term->name . '</a></li>';
    
    }
    echo '</ul>';
    

    so it looks like you are trying to echo the WP_Error object.

    You could try to debug it with:

    if( is_wp_error( $term_link ) )    
        echo $term_link->get_error_message();
    
  2. Even though you are doing AJAX wrong, that isn’t your problem. The problem is this line:

    $wpdb = new wpdb( DB_USER , DB_PASSWORD , DB_NAME , DB_HOST );
    

    But I don’t see why you need either of these:

    require_once( 'wp-includes/wp-db.php' );
    $wpdb = new wpdb( DB_USER , DB_PASSWORD , DB_NAME , DB_HOST );
    

    Try the code without those lines and it works, at least when I try.

    But please do AJAX right.

Comments are closed.