Error fatal capturable en PHP: El objeto de clase WP_Error no se pudo convertir a string

12 jun 2017, 14:02:44
Vistas: 42.3K
Votos: 6

Necesito ayuda con esto:

Error fatal capturable en PHP: El objeto de clase WP_Error no se pudo convertir a string en /hosting/www/ortopediairati.es/public/wp-content/themes/irati/rt-framework/functions/rt_breadcrumb.php en la línea 58

He actualizado a WordPress 4.8 y el sitio web no está funcionando bien.

El archivo completo está aquí:

<?php

/* Función RT-Breadcrumb */
function rt_breadcrumb(){
global $taxonomy,$term_slug,$post,$delimiter;

if(!get_option('rttheme_breadcrumb_menus')){
    return false;
}

//Marcado
$before='<div class="breadcrumb">'.wpml_t(THEMESLUG, 'Texto del Menú Breadcrumb', get_option(THEMESLUG.'_breadcrumb_text')).' ';
$after='</div>';
$delimiter=' | ';

/* Breadcrumb de WooCommerce */
if ( function_exists( 'woocommerce_breadcrumb' ) ) {
    if( is_woocommerce() ){
        $defaults = array(
            'delimiter'  => $delimiter,
            'wrap_before'  => $before,
            'wrap_after' => $after,
            'before'   => '',
            'after'   => '',
            'home'    => null
        );

        woocommerce_breadcrumb($defaults); 
        return false;
    }
} 


echo $before;

//Página de Inicio
echo "<a href=\"". BLOGURL ."\" title=\"". get_bloginfo('name')."\">".__( 'Inicio', 'rt_theme' )."</a>";

// función para páginas padre
function page_parents($parent_page_id,$child_pages){
    global $delimiter;

    $parent_page = get_page($parent_page_id);
    $page_parents = $delimiter."<a href=\"".get_permalink($parent_page->ID)."\" title=\"". get_the_title($parent_page->ID) ."\" >". get_the_title($parent_page->ID) ."</a>" .$child_pages;

    if ($parent_page->post_parent) page_parents($parent_page->post_parent,$page_parents);

    else echo $page_parents;

}


// función para términos padre
function term_parents($term_id,$child_terms){
    global $taxonomy,$delimiter;

    $parent_term = get_term_by('ID',$term_id, $taxonomy);
    $term_parents = $delimiter."<a href=\"".get_term_link($parent_term->slug,$taxonomy)."\" title=\"". $parent_term->name ."\" >". $parent_term->name ."</a>" .$child_terms;

    if ($parent_term->parent) term_parents($parent_term -> parent,$term_parents);

    else echo $term_parents;

}

//obtener página de inicio
function get_start_page($start_page){
    global $delimiter;

    //páginas padre de inicio
    $get_start_page=get_page($start_page);
    if ($get_start_page -> post_parent){
        page_parents( $get_start_page -> post_parent,''); 
    }

    //página de inicio
    if ($start_page && !get_query_var('lang')) {
        echo  $delimiter."<a href=\"".get_permalink($start_page)."\" title=\"". get_the_title($start_page) ."\" >". get_the_title($start_page) ."</a>";
    }
}

//términos
function term_links(){
    global $taxonomy,$post_type,$term_slug,$delimiter;

    //Encontrar página de inicio y definir nombres de taxonomía
    if($taxonomy=="product_categories"){
        $start_page=get_option('rttheme_product_list');
    }elseif($taxonomy=="portfolio_categories"){
        $start_page=get_option('rttheme_portf_page');
    }   

    //obtener página de inicio
    if ($start_page) get_start_page($start_page);


    $term=get_term_by('slug',$term_slug, $taxonomy);

    //términos padre
    if (is_object($term) && $term -> parent){
        echo term_parents($term -> parent,'');   
    } 

    //término actual
    if(is_object($term) && $term->slug) echo  $delimiter."<a href=\"".get_term_link($term->slug,$taxonomy)."\" title=\"". $term->name ."\" >". $term->name ."</a>";
}



//Páginas
if ( is_page() ){
    //páginas padre
    if ($post -> post_parent){
        page_parents( $post -> post_parent,''); 
    } 

    //página actual
    echo  $delimiter ."". $post->post_title;
}

//Individual
elseif (is_single() && !is_attachment()){ 
    // Obtener tipo de entrada
    $post_type = get_post_type();

    //Taxonomías
    if($post_type == 'products' || $post_type == 'portfolio'){

        term_links();
        //página actual
        echo  $delimiter."<a href=\"".get_permalink()."\" title=\"". get_the_title() ."\" >". get_the_title() ."</a>";

    }else{
    //Categorías

    //página de inicio
    $start_page=get_option('rttheme_blog_page');

    //obtener página de inicio
    if ($start_page) get_start_page($start_page);

        $category_id = get_the_category();
        $category_id = $category_id[0]->cat_ID;//solo una categoría puede mostrarse en la lista - la primera
        echo $delimiter;
        if($category_id){
            echo get_category_parents($category_id, TRUE, $delimiter, FALSE );
        }
        echo $post->post_title;
    }

//Categoría
}elseif (is_category()){
    //página de inicio
    $start_page=get_option('rttheme_blog_page');

    //obtener página de inicio
    if ($start_page) get_start_page($start_page);

        echo $delimiter."".get_category_parents(get_query_var('cat'), TRUE, $delimiter, FALSE);

//Taxonomía
}elseif (is_tax()){
    term_links();
} else {
    echo  $delimiter."";
    wp_title('');
}

echo $after;

wp_reset_query(); 
}
?>

¿Alguien podría ayudarme?

1
Comentarios

¿Qué hay en la línea 58 de la función mencionada en el error? En algún punto, algo está devolviendo un WP_Error y está siendo convertido a una cadena de texto.

Welcher Welcher
12 jun 2017 14:17:46
Todas las respuestas a la pregunta 1
0
16

La línea 58, como indica el error, es esta línea:

$parent_term = get_term_by('ID',$term_id, $taxonomy);
$term_parents = $delimiter."<a href=\"".get_term_link($parent_term->slug,$taxonomy)."\" title=\"". $parent_term->name ."\" >". $parent_term->name ."</a>" .$child_terms;

Y nuestro error es:

Object of class WP_Error could not be converted to string

Lo que significa que uno de esos elementos que se están concatenando no es un "string", sino un objeto WP_Error.

Sospecharía de get_term_link, que probablemente es lo que está devolviendo el objeto de error, lo que sugiere que:

  • el término no existe
  • la taxonomía no está registrada o no es válida
  • los valores que se pasan están vacíos inesperadamente
  • $parent_term no es un término, sino un objeto de error

Lo que nos lleva a la lección aquí:

A veces las funciones devuelven objetos de error y hay que comprobarlo, no asumas que todo ha ido bien

Cómo comprobar errores

Tomemos un ejemplo que siempre fallará:

$value = get_term_link( "not a real term","fake taxonomy" );
if ( is_wp_error( $value ) ) {
    // algo salió mal
}

is_wp_error será verdadero si $value es un objeto de error. Algunas funciones pueden devolver false o null, así que !empty( $value ) también es una comprobación útil

Los objetos de error pueden contener códigos y mensajes de error, y puedes usar el método get_error_message() para mostrarlos:

$value = get_term_link( "not a real term","fake taxonomy" );
if ( is_wp_error( $value ) ) {
    // algo salió mal
    echo $value->get_error_message();
}

También podrías establecer $value manualmente a un valor por defecto

Una nota final sobre globales

El código hace uso de variables globales, pero estas variables tienen nombres muy genéricos como $taxonomy. Otros plugins también pueden usarlas, y pueden entrar en conflicto. Lo mismo ocurre con los nombres de funciones.

Mejor

Préfijalas:

// función de términos padres
function sergi_term_parents( $term_id, $child_terms ) {
    global $sergi_taxonomy, $sergi_delimiter;

Óptimo

Usa inyección de dependencias y elimina las globales por completo:

// función de términos padres
function sergi_term_parents( $term_id, $child_terms, $taxonomy, $delimeter ){

Ahora tu función term_parents nunca entrará en conflicto y funcionará para cualquier taxonomía o delimitador

12 jun 2017 16:22:54