Creating Wordpress Category at the time of Theme Activation

自古美人都是妖i 提交于 2019-12-06 16:09:33

The action create_category runs when a new category is created.

You want your category creation function to run when the theme is activated. The relevant action is after_setup_theme.

Drop this in your theme's functions.php and you should be good to go:

function create_my_cat () {
    if (file_exists (ABSPATH.'/wp-admin/includes/taxonomy.php')) {
        require_once (ABSPATH.'/wp-admin/includes/taxonomy.php'); 
        if ( ! get_cat_ID( 'Testimonials' ) ) {
            wp_create_category( 'Testimonials' );
        }
    }
}
add_action ( 'after_setup_theme', 'create_my_cat' );

Note: If you have already used a function my_theme_name_setup() {} you don't need another function. One more *note to mention; you can also use category_exists instead of get_cat_ID(), so the full code example is:

function my_theme_name_setup() {

    if( file_exists( ABSPATH . '/wp-admin/includes/taxonomy.php' ) ) :
        require_once( ABSPATH . '/wp-admin/includes/taxonomy.php' );

            if( ! category_exists( 'name' ) ) :

                wp_create_category( 'name' );

            endif;// Category exists

    endif;// File exists 

}
add_action( 'after_setup_theme', 'my_theme_name_setup' );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!