插件:注册定制帖子类型、儿童就绪和性能最佳实践

时间:2015-09-08 作者:Antonio

对于为我的主题添加一些自定义帖子类型的插件,我会在性能、干净代码和子主题方面找到最佳实践。

你觉得这样的事情怎么样?

if ( ! function_exists( \'custom_taxonomy_1\' ) ) {

    function custom_taxonomy_1() {

        $args = array(
            ...
        );
        register_taxonomy( \'custom_taxonomy_1\', array( \'custom_post_type_1\' ), $args );
    }
}

if ( ! function_exists( \'custom_post_type_1\' ) ) {

    function custom_post_type_1() {

        $args = array(
            ...
        );
         register_post_type( \'custom_post_type_1\', $args );
    }
}

if ( ! function_exists( \'custom_post_type_2\' ) ) {

    function custom_post_type_2() {

        $args = array(
            ...
        );
        register_post_type( \'custom_post_type_2\', $args );
    }
}



if ( ! function_exists(\'my_init_register_types\') ) {
    function my_init_register_types(){
        custom_taxonomy_1();
        custom_post_type_1();
        custom_post_type_2();
    }

    add_action( \'init\', \'my_init_register_types\' );
}

1 个回复
最合适的回答,由SO网友:Pieter Goosen 整理而成

关于代码的一些想法

有条件的function_exists() 实际上永远不会工作,因为插件是先加载的,然后是子主题函数,然后是父主题函数。您可以放弃这些条件检查。这个function_exists() 该函数主要用于父主题,并允许插件或子主题覆盖该函数

在一个函数中注册所有分类法和自定义帖子类型,然后将该函数挂接到init. 这比让10个函数做几乎相同的事情更有意义init

在插件中使用插件名称作为函数名称的前缀,这将确保唯一性,并避免将来出现致命错误。您问题中的示例名称很容易复制,如果任何其他插件使用相同的名称,这将破坏站点。

由于这是一个插件,我只需要使用一个闭包,这样就不需要任何唯一的函数名。示例:

add_action( \'init\', function () 
{
    // Your code to register taxonomies and custom post types here
});

相关推荐

Admin Theme customization

我遵循wordpress codex网站上关于通过插件创建管理主题的说明。我激活了插件,但我的样式表没有包含在<head>.. 这是我的代码:add_action( \'admin_init\', \'kd_plugin_admin_init\' ); add_action( \'admin_menu\', \'kd_plugin_admin_menu\' ); function kd_plugin_admin_init() { /* Register