Как добавить элемент по умолчанию в пользовательскую таксономию?


В таксономии Wordpress по умолчанию (Категории) элемент по умолчанию не классифицирован. Как добавить элемент по умолчанию в новую пользовательскую таксономию?

Functions.php:

// === CUSTOM TAXONOMIES === //
function my_custom_taxonomies() {
    register_taxonomy(
        'block',        // internal name = machine-readable taxonomy name
        'static_content',       // object type = post, page, link, or custom post-type
        array(
            'hierarchical' => true,
            'labels' => array(
                'name' => __( 'Blocks' ),
                'singular_name' => __( 'Block' ),
                'add_new_item' => 'Add New Block',
                'edit_item' => 'Edit Block',
                'new_item' => 'New Block',
                'search_items' => 'Search Block',
                'not_found' => 'No Block found',
                'not_found_in_trash' => 'No Block found in trash',
            ),
            'query_var' => true,    // enable taxonomy-specific querying
            'rewrite' => array( 'slug' => 'block' ),    // pretty permalinks for your taxonomy?
        )
    );
}
add_action('init', 'my_custom_taxonomies', 0);

РЕДАКТИРОВАТЬ: Я просто хочу, чтобы элемент таксономии был там, когда тема будет установлена. Его не нужно автоматически добавлять к какому-либо пустому термину.

 10
Author: janoChen, 2011-01-18

4 answers

Посмотрите здесь:

Https://web.archive.org/web/20150403012347/http://wordpress.mfields.org/2010/set-default-terms-for-your-custom-taxonomies-in-wordpress-3-0/

В основном, что вам нужно сделать, это использовать крючок save_post, чтобы проверить условия для публикации и добавить термин по умолчанию из вашей таксономии, если он пустой.

Если вы просто хотите иметь начальный набор терминов в своей пользовательской таксономии, то вы можете использовать wp_insert_term(). Наверное, проще всего добавить его в тот же функция, которую вы используете для создания собственной таксономии. Как добавляет t3ios в комментариях, вы должны сначала вызвать get_term() и вставить термин только в том случае, если возвращаемое значение равно нулю (т. Е. Термин не существует).

Этот пример кода взят из Кодекса: http://codex.wordpress.org/Function_Reference/wp_insert_term

$parent_term = term_exists( 'fruits', 'product' ); // array is returned if taxonomy is given
$parent_term_id = $parent_term['term_id']; // get numeric term id
wp_insert_term(
  'Apple', // the term 
  'product', // the taxonomy
  array(
    'description'=> 'A yummy apple.', 
    'slug' => 'apple', 
    'parent'=> $parent_term_id
  )
);
 8
Author: anu, 2018-09-11 16:24:09

Категория по умолчанию - жестко заданный регистр в wp_insert_post() функция.

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

 4
Author: Rarst, 2011-01-18 11:41:28

Мне нужно было заполнить пользовательскую таксономию "Дни" днями недели..Я не хотел, чтобы клиенту приходилось возиться с созданием дней, или входить туда и удалять дни или писать дни с ошибками. Следуя приведенному выше совету, я придумал это, но мне интересно, есть ли более краткий способ его кодирования:

 /*************************************** ...Create a Custom Taxonomy for days ******************************/
add_action( 'init', 'build_taxonomies', 0 );  
function build_taxonomies() {  
    register_taxonomy( 
    'days', 
    'schedule',
   array( 'hierarchical' => true, 
    'label' => 'Days',
    'query_var' => true, 
    'show_ui' => false, //removes the menus from admin menu and edit panel  
    'rewrite' => true ) );  

/*---------------------------------------Check to see if the days are created..if not, create them----*/
$parent_term = term_exists( 'days', 'days' ); // array is returned if taxonomy is given
$parent_term_id = $parent_term['term_id']; // get numeric term id

wp_insert_term(//this should probably be an array, but I kept getting errors..
        'Monday', // the term 
        'days', // the taxonomy
        array(
        'slug' => 'monday',
        'parent'=> $parent_term_id ));

wp_insert_term(
        'Tuesday', // the term 
        'days', // the taxonomy
        array(
        'slug' => 'tuesday',
        'parent'=> $parent_term_id ));

wp_insert_term(
        'Wednesday', // the term 
        'days', // the taxonomy
        array(
        'slug' => 'wednesday',
        'parent'=> $parent_term_id ));

wp_insert_term(
        'Thursday', // the term 
        'days', // the taxonomy
        array(
        'slug' => 'thursday',
        'parent'=> $parent_term_id ));

wp_insert_term(
        'Friday', // the term 
        'days', // the taxonomy
        array(
        'slug' => 'friday',
        'parent'=> $parent_term_id ));

wp_insert_term(
        'Saturday', // the term 
        'days', // the taxonomy
        array(
        'slug' => 'saturday',
        'parent'=> $parent_term_id ));

wp_insert_term(
        'Sunday', // the term 
        'days', // the taxonomy
        array(
        'slug' => 'sunday',
        'parent'=> $parent_term_id ));
}
/************ now I add my own meta box for days to get rid of extra controls *************/

add_action('admin_menu', 'add_custom_categories_box');
function add_custom_categories_box() {
 add_meta_box('myrelateddiv', 'Days*', 'ilc_post_related_meta_box', 'schedule', 'normal', 'low', array( 'taxonomy' => 'days' ));
}

function ilc_post_related_meta_box( $post, $box ) {
  $defaults = array('taxonomy' => 'related');
  if ( !isset($box['args']) || !is_array($box['args']) )
  $args = array();
  else
  $args = $box['args'];
  extract( wp_parse_args($args, $defaults), EXTR_SKIP );
  $tax = get_taxonomy($taxonomy);
?>

  <ul id="<?php echo $taxonomy; ?>checklist" class="list:<?php echo $taxonomy?> categorychecklist form-no-clear">
<?php
  wp_terms_checklist($post->ID, array( 'taxonomy' => $taxonomy, 'popular_cats' => $popular_ids, 'checked_ontop' => FALSE ) )
?>
</ul>   
 1
Author: endle.winters, 2018-08-21 05:24:54

Используя плагин Термин по умолчанию , вы могли бы сделать это

register_taxonomy( 'custom-tax', array('post'), array(
    'label'              => 'Custom Tag',
    'public'             => true,
    'show_ui'            => true,
    'default_term'       => 'Some Default Term', // Add this line to your code 
// then activate and deactivate the default term plugin to save the terms you set.
));

По умолчанию при отправке сообщения в сообщение будет сохранен термин по умолчанию, если термин не отмечен. Это работает как для иерархических, так и для неиерархических таксономий.

 0
Author: Allan Christian Carlos, 2016-08-07 04:38:37