tonik / theme

Tonik is a WordPress Starter Theme which aims to modernize, organize and enhance some aspects of WordPress theme development.
http://labs.tonik.pl/theme/
MIT License
1.33k stars 140 forks source link

Custom post type helper class doesn't work #31

Closed msacchetti closed 7 years ago

msacchetti commented 7 years ago

I am using https://github.com/jjgrainger/wp-custom-post-type-class . It works in every way except for the "has_archive" option is ignored. I found a similar issue in their repo that i think may be the problem (linked below). Is there any way i can use this class in this theme?

"I suspect the problem is that I initialize a theme using an init class, hooked to after_theme_setup. Putting the class inside a class was probably creating unpredictable results."

"new CPT() should not be included in a hook, it sets up the hooks in __construct, so if you are using CPT in a hook then it's probably not working at all and being loaded too late."

https://github.com/jjgrainger/wp-custom-post-type-class/issues/26

jedrzejchalubek commented 7 years ago

It is not ideal that this class hooks at object construct. It would be better if this was left to the developer.

But, it is no big deal. We only have to hook earlier than this library and it is a great use case for service container :) Plugin uses init action, so we will use after_setup_theme action to setup everything so it will be ready at init.

Bind service, which creates CPT class instance:

// @ app/Setup/services.php

use CPT;
use function App\Theme\theme;

function bind_stores_post_type_service()
{
    theme()->bind('posttype.stores', function (Theme $theme, $parameters) {
        return new CPT('store');
    });
}
add_action('after_setup_theme', 'App\Theme\Setup\bind_stores_post_type_service');

Register post type itself using our service:

// @ app/Structure/posttypes.php

use function App\Theme\theme;
use function App\Theme\config;

function register_store_post_type()
{
    $stores = theme('posttype.stores');

    // Make all required configuration...
    $stores->set_textdomain(config('textdomain'));
}
add_action('after_setup_theme', 'App\Theme\Structure\register_store_post_type');

Register taxonomy for our stores post type using the same service:

// @ app/Structure/taxonomies.php

use function App\Theme\theme;
use function App\Theme\config;

function register_store_address_taxonomy()
{
    $stores = theme('posttype.stores');

    $stores->register_taxonomy([
        'taxonomy_name' => 'address',
        'singular' => 'Address',
        'plural' => 'Addresses',
        'slug' => 'address'
    ]);
}
add_action('after_setup_theme', 'App\Theme\Structure\register_store_address_taxonomy');
msacchetti commented 7 years ago

Thank you!