1

I'm registering custom post type in the plugin, but want to allow users of the plugin modify it afterwards (e.g. if they are installing for clients, etc.)

function create_reviews_post_type() {
    register_post_type('reviews', array(
        'labels' => array(
            'name' => __('Reviews'),
            'singular_name' => __('Review')
            ),
        'public' => true,
        'has_archive' => true,
        )
    );
}
add_action('init', 'create_reviews_post_type');

What is best way to achieve this? E.g. I want to change name, singular name and slug in future.

I understand that there is a similar question, but

  1. it 5 years old and I hope there can be an easier way,
  2. it doesn't cover the name part
1

WordPress provides the register_post_type_args filter to let users do this:

function wpd_modify_post_type( $args, $post_type ){
    if( 'reviews' == $post_type ){
        $args['labels']['name'] = 'New name';
        $args['labels']['singular_name'] = 'New singular name';
        $args['rewrite']['slug'] = 'new-slug';
    }
    return $args;
}
add_filter( 'register_post_type_args', 'wpd_modify_post_type', 10, 2 );

Keep in mind that if the slug changes, the user will need to flush rewrite rules manually for the new slug to start working, which can be done by visiting the Settings > Permalinks page in admin.

3

You could do something simple like providing them filters to modify.

function create_reviews_post_type() {
    $slug = apply_filters('plugin_cpt_slug','reviews');
    $name = apply_filters('plugin_cpt_name','Reviews');
    $sname = apply_filters('plugin_cpt_name_singular','Review');

    register_post_type($slug, array(
        'labels' => array(
            'name' => __($name),
            'singular_name' => __($sname)
            ),
        'public' => true,
        'has_archive' => true,
        )
    );
}
add_action('init', 'create_reviews_post_type');

They can modify them using add_filter() like so:

add_filter('plugin_cpt_slug','change_plugin_cpt_slug');
function change_plugin_cpt_slug(){
    return 'complaints';
}
//etc., etc.

This is admittedly a verbose way of doing this, but it works.

  • Thanks, I get the errors though: $slug, $name, $sname are undefined; register_post_type is called incorrectly – Runnick Jun 27 '17 at 20:28
  • Well first of all you should change those, I used generic identifiers as an example. Change them to something more specific to your plugin. Secondly, I edited the answer. – Spartacus Jun 27 '17 at 20:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.