Как я могу решить Неустранимая ошибка: невозможно переобъявить функцию... в функции короткого кода WordPress

«Мне нужно отобразить вложенные дочерние таксономии и перечислить их сообщения. Вот что я пытаюсь получить Это работает, но мне нужно использовать эту функцию как шорткод. Получение сообщения «Неустранимая ошибка: невозможно переопределить функцию...» при сохранении страницы с этой функцией в виде короткого кода.

Вот полная ошибка при сохранении страницы:

«Неустранимая ошибка: невозможно повторно объявить get_child_categories() (ранее объявленное в /nas/content/live/resonate2022/wp-content/themes/ResonateHealth-Theme/content/masterguide-categorylist.php:3) в /nas/content/live/ resonate2022/wp-content/themes/ResonateHealth-Theme/content/masterguide-categorylist.php в строке 3"

Вот моя функция/файл "masterguide-categories.php"

<?php
function get_child_categories( $parent_category_id ){
    $html = '';
    $child_categories = get_categories( array( 'parent' => $parent_category_id, 'hide_empty' => true, 'taxonomy' => 'masterguidecategory' ) );
    if ( !empty( $child_categories ) ){
    $html .= '<ul class = "children">';
    foreach ( $child_categories as $child_category ) {
        $html .= '<li class = "child">'.$child_category->name;
        $child_categories = get_term_children($child_category->term_id, 'masterguidecategory');

        if (!empty($child_categories)){
             $html .= get_child_categories( $child_category->term_id );
        }else{
             $html .= get_posts_for_lastchild($child_category->term_id);
        }
        $html .= '</li>';
    }
$html .= '</ul>';
} 
return $html;
}

function get_posts_for_lastchild($category_id ){
    $args = array('post_type' => 'masterguide','posts_per_page'=>'-1', 'orderby' => 'title', 'order' => 'ASC', 'tax_query' => array(array('taxonomy' => 'masterguidecategory' ,'field' => 'term_id', 'terms' => $category_id)));
    $postquery = new WP_Query( $args );
    if ($postquery->have_posts()) :
        $html .= '<ul class = "children ChartPostList">';
    while ($postquery->have_posts()) : $postquery->the_post();
        $html .= '<li class = "ChartPostListItem"><a class = "button small" href='.get_the_permalink().'>'.get_the_title().'</a></li>';
    endwhile;
         $html .= '</ul>';
    endif;
    return $html;
}

function list_categories(){
    $html = '';
    $parent_categories = get_categories( array( 'parent' => 0, 'hide_empty' => true, 'taxonomy' => 'masterguidecategory' ) );
    $html.= '<ul class = "chartAccordion">';
    foreach ( $parent_categories as $parent_category ) {
        $html .= '<li class = "parent">'.$parent_category->name;
        $child_categories = get_term_children($parent_category->term_id, 'masterguidecategory');
        if (!empty($child_categories)){
             $html .= get_child_categories( $parent_category->term_id  );
        }else{
             $html .= get_posts_for_lastchild($parent_category->term_id);
        }
     $html .= '</li>';
     }
     $html.= '</ul>';
     return $html;
}
echo list_categories();
?>

Затем в "functions.php"

function mg_catlist_function(){
    ob_start();
    get_template_part( 'content/masterguide', 'categorylist' );
    $content = ob_get_clean();
    return $content;
}
add_shortcode('mg_categories','mg_catlist_function');
Как убрать количество товаров в категории WooCommerce
Как убрать количество товаров в категории WooCommerce
По умолчанию WooCommerce показывает количество товаров рядом с категорией, как показано ниже.
0
0
50
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Использование функций в шаблонах — не лучшая практика, поэтому вам следует провести рефакторинг кода.

Однако есть быстрое решение вашей проблемы: вы можете объявить функцию, только если она еще не объявлена, сделайте это:

<?php
if (!function_exists('get_child_categories')) {
    function get_child_categories( $parent_category_id ){
        /// your code here
    }
}
if (!function_exists('get_posts_for_lastchild')) {
    function get_posts_for_lastchild( $category_id ){
        /// your code here
    }
}
if (!function_exists('list_categories')) {
    function list_categories(){
        /// your code here
    }
}
echo list_categories();

Таким образом вы решите свою текущую проблему, но помните, что функции никогда не должны находиться в шаблонах.

Другие вопросы по теме