WordPress - не может создать таксономию внутри условного оператора - PullRequest
3 голосов
/ 07 июня 2019

Моя цель состоит в том, чтобы внутри плагина вытащить все посты / страницы / пользовательские типы постов в проекте и создать собственную таксономию, если она не существует.Всякий раз, когда плагин входит в оператор if, php перестает работать на странице.Как вы можете видеть в выражении foreach, я повторяю имя типа записи и связанную с ним таксономию.

Я просто хочу создать пользовательскую таксономию для общедоступного типа записи, если таксономия не существует.

Я могу запустить код таксономии, который находится внутри оператора if внутри файла functions.php, пока я заменяю переменные соответствующими типами записей.

Я также попытался вместо использования add_action ('init', 'custom_taxo_cpt_taxonomy', 1);просто вызовите функцию напрямую через custom_taxo_cpt_taxonomy () в той же строке, что и add_action ('init', 'custom_taxo_cpt_taxonomy', 1);

echos / var_dumps могут дать мне типы записей и таксономии, связанные без проблемна странице, так что я знаю, что хорошо тянется на странице.

<?php
$args = array(
    'public'   => true,
);

$output = 'names';
$operator = 'and';

$post_types = get_post_types( $args, $output, $operator ); 

foreach ( $post_types  as $post_type ) {
    $cpt_taxo_ar = get_object_taxonomies($post_type);
    $cpt_taxo_ar = array_shift($cpt_taxo_ar);
    echo '<p>' . $post_type . ' category: ' . $cpt_taxo_ar . '</p>';
    if($cpt_taxo_ar != $post_type . '_custom_taxo'){
        echo $post_type . '_custom_taxo';

        // Register CustomTaxo Tags Taxonomy
        function custom_taxo_cpt_taxonomy() {

            $labels = array(
                'name'                       => _x( 'CustomTaxo Tags', 'CustomTaxo Tags', 'custom_taxo_domain' ),
                'singular_name'              => _x( 'CustomTaxo Tag', 'CustomTaxo Tag', 'custom_taxo_domain' ),
                'menu_name'                  => __( 'CustomTaxo Tags', 'custom_taxo_domain' ),
                'all_items'                  => __( 'All Tags', 'custom_taxo_domain' ),
                'parent_item'                => __( 'Parent Tag', 'custom_taxo_domain' ),
                'parent_item_colon'          => __( 'Parent Tag:', 'custom_taxo_domain' ),
                'new_item_name'              => __( 'New Tag Name', 'custom_taxo_domain' ),
                'add_new_item'               => __( 'Add New Tag', 'custom_taxo_domain' ),
                'edit_item'                  => __( 'Edit Tag', 'custom_taxo_domain' ),
                'update_item'                => __( 'Update Tag', 'custom_taxo_domain' ),
                'view_item'                  => __( 'View Tag', 'custom_taxo_domain' ),
                'separate_items_with_commas' => __( 'Separate items with commas', 'custom_taxo_domain' ),
                'add_or_remove_items'        => __( 'Add or remove tags', 'custom_taxo_domain' ),
                'choose_from_most_used'      => __( 'Choose from the most used', 'custom_taxo_domain' ),
                'popular_items'              => __( 'Popular tags', 'custom_taxo_domain' ),
                'search_items'               => __( 'Search tags', 'custom_taxo_domain' ),
                'not_found'                  => __( 'Not Found', 'custom_taxo_domain' ),
                'no_terms'                   => __( 'No items', 'custom_taxo_domain' ),
                'items_list'                 => __( 'Tags list', 'custom_taxo_domain' ),
                'items_list_navigation'      => __( 'Tags list navigation', 'custom_taxo_domain' ),
            );

            $args = array(
                'labels'                     => $labels,
                'hierarchical'               => false,
                'public'                     => true,
                'show_ui'                    => true,
                'show_admin_column'          => true,
            );

            register_taxonomy( $post_type . '_custom_taxo', 'page', $args );

        } // end taxo function
            add_action( 'init', 'custom_taxo_cpt_taxonomy', 1 );
    } //end for loop
}
?>

1 Ответ

0 голосов
/ 07 июня 2019

Согласно документации:

add_action( string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1 )`

Для решения проблемы: "Cannot redeclare custom_taxo_cpt_taxonomy()"

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

$custom_taxo_cpt_taxonomy = function() { ... }

Наконец, анонимный не работает, потому что WordPress использует call_user_func_array в class-wp-hook в apply_filters, а не как $myCallback();

РЕДАКТИРОВАТЬ: функция не анонимная вне цикла

<?php
function custom_taxo_cpt_taxonomy($params) {
  register_taxonomy( $params['post_type'] . '_custom_taxo', 'page', $params['args'] );
} // end taxo function


foreach ( $post_types  as $post_type ) {
  $cpt_taxo_ar = get_object_taxonomies($post_type);
  $cpt_taxo_ar = array_shift($cpt_taxo_ar);
  echo '<p>' . $post_type . ' category: ' . $cpt_taxo_ar . '</p>';

  if($cpt_taxo_ar != $post_type . '_custom_taxo'){
    echo $post_type . '_custom_taxo';

    // Register CustomTaxo Tags Taxonomy
    // function custom_taxo_cpt_taxonomy() { <= issue here
    // $custom_taxo_cpt_taxonomy = function() { <= other issue
    $labels = array(
      'name'                       => _x( 'CustomTaxo Tags', 'CustomTaxo Tags', 'custom_taxo_domain' ),
      'singular_name'              => _x( 'CustomTaxo Tag', 'CustomTaxo Tag', 'custom_taxo_domain' ),
      'menu_name'                  => __( 'CustomTaxo Tags', 'custom_taxo_domain' ),
      'all_items'                  => __( 'All Tags', 'custom_taxo_domain' ),
      'parent_item'                => __( 'Parent Tag', 'custom_taxo_domain' ),
      'parent_item_colon'          => __( 'Parent Tag:', 'custom_taxo_domain' ),
      'new_item_name'              => __( 'New Tag Name', 'custom_taxo_domain' ),
      'add_new_item'               => __( 'Add New Tag', 'custom_taxo_domain' ),
      'edit_item'                  => __( 'Edit Tag', 'custom_taxo_domain' ),
      'update_item'                => __( 'Update Tag', 'custom_taxo_domain' ),
      'view_item'                  => __( 'View Tag', 'custom_taxo_domain' ),
      'separate_items_with_commas' => __( 'Separate items with commas', 'custom_taxo_domain' ),
      'add_or_remove_items'        => __( 'Add or remove tags', 'custom_taxo_domain' ),
      'choose_from_most_used'      => __( 'Choose from the most used', 'custom_taxo_domain' ),
      'popular_items'              => __( 'Popular tags', 'custom_taxo_domain' ),
      'search_items'               => __( 'Search tags', 'custom_taxo_domain' ),
      'not_found'                  => __( 'Not Found', 'custom_taxo_domain' ),
      'no_terms'                   => __( 'No items', 'custom_taxo_domain' ),
      'items_list'                 => __( 'Tags list', 'custom_taxo_domain' ),
      'items_list_navigation'      => __( 'Tags list navigation', 'custom_taxo_domain' )
    );

    $args = array(
        'labels'                     => $labels,
        'hierarchical'               => false,
        'public'                     => true,
        'show_ui'                    => true,
        'show_admin_column'          => true
    );

    $params = array(
      'post_type' => $post_type,
      'args' => $args
    );

    // Pass callable not anonymous function
    add_action( 'init', array('custom_taxo_cpt_taxonomy', $params), 1);
  } //end for loop
}
?>

РЕДАКТИРОВАТЬ: ВАЖНО

Так что код ниже не работает : syntax error, unexpected 'add_action' (T_STRING).

<?php
$args = array(
  'public' => true
);

$output = 'names';
$operator = 'and';

$post_types = get_post_types( $args, $output, $operator ); 

foreach ( $post_types  as $post_type ) {
    $cpt_taxo_ar = get_object_taxonomies($post_type);
    $cpt_taxo_ar = array_shift($cpt_taxo_ar);
    echo '<p>' . $post_type . ' category: ' . $cpt_taxo_ar . '</p>';
    if($cpt_taxo_ar != $post_type . '_custom_taxo'){
        echo $post_type . '_custom_taxo';

        // Register CustomTaxo Tags Taxonomy
        // function custom_taxo_cpt_taxonomy() { <= issue here
        // Create anonymous function
        $custom_taxo_cpt_taxonomy = function() {

            $labels = array(
                'name'                       => _x( 'CustomTaxo Tags', 'CustomTaxo Tags', 'custom_taxo_domain' ),
                'singular_name'              => _x( 'CustomTaxo Tag', 'CustomTaxo Tag', 'custom_taxo_domain' ),
                'menu_name'                  => __( 'CustomTaxo Tags', 'custom_taxo_domain' ),
                'all_items'                  => __( 'All Tags', 'custom_taxo_domain' ),
                'parent_item'                => __( 'Parent Tag', 'custom_taxo_domain' ),
                'parent_item_colon'          => __( 'Parent Tag:', 'custom_taxo_domain' ),
                'new_item_name'              => __( 'New Tag Name', 'custom_taxo_domain' ),
                'add_new_item'               => __( 'Add New Tag', 'custom_taxo_domain' ),
                'edit_item'                  => __( 'Edit Tag', 'custom_taxo_domain' ),
                'update_item'                => __( 'Update Tag', 'custom_taxo_domain' ),
                'view_item'                  => __( 'View Tag', 'custom_taxo_domain' ),
                'separate_items_with_commas' => __( 'Separate items with commas', 'custom_taxo_domain' ),
                'add_or_remove_items'        => __( 'Add or remove tags', 'custom_taxo_domain' ),
                'choose_from_most_used'      => __( 'Choose from the most used', 'custom_taxo_domain' ),
                'popular_items'              => __( 'Popular tags', 'custom_taxo_domain' ),
                'search_items'               => __( 'Search tags', 'custom_taxo_domain' ),
                'not_found'                  => __( 'Not Found', 'custom_taxo_domain' ),
                'no_terms'                   => __( 'No items', 'custom_taxo_domain' ),
                'items_list'                 => __( 'Tags list', 'custom_taxo_domain' ),
                'items_list_navigation'      => __( 'Tags list navigation', 'custom_taxo_domain' )
            );

            $args = array(
                'labels'                     => $labels,
                'hierarchical'               => false,
                'public'                     => true,
                'show_ui'                    => true,
                'show_admin_column'          => true
            );

            register_taxonomy( $post_type . '_custom_taxo', 'page', $args );

        } // end taxo function

        // Pass callable anonymous function
        add_action( 'init', $custom_taxo_cpt_taxonomy, 1 );
    } //end for loop
}
?>

, в конце массива создает дополнительное пустое поле.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...