0

I'm trying to create archive pages for my custom post type. I create custom post types from within custom classes:

functions.php

include_once(get_template_directory() . '/admin/admin_init.php');

admin_init.php

include_once(ADMIN_CPT_DIR . '/CPT.php');

CPT.php

class CPT
{
    protected $cpt_name;

    public function __construct($cpt_name)
    {
        $this->cpt_name = $cpt_name;
        add_action('init', array( $this, 'cpt_init' ) );
    }

    public function cpt_init()
   {
        $labels = array(
        'name' => __('custom_name', 'textDomain'),
        'singular_name' => __('custom_name', 'textDomain')
         );

        $args = array(
        'labels' => $labels,
        'public' => true,
        'has_archive' => true,
        'publicly_queryable' => true,
        'exclude_from_search' => false,
        'show_ui' => true,
        'show_in_menu' => true,
        'has_archive' => true,
        'query_var' => true,
        'rewrite' => array('slug' => 'custom_name'),
        'supports' =>array('title','editor', 'custom-fields','thumbnail')
    );

    register_post_type( $this->cpt_name, $args );
   }
}

if( is_admin() )
    $cpt = new CPT('cpt_child');

The custom post type is registered and all works fine, but I always get a 404 when trying to access the archive page (archive-custom_name.php).

If I take the inner part of the cpt_init - method and put it into the functions.php like so:

add_action( 'init', 'create_post_type' );

    function create_post_type()
    {
        $labels = array(
        'name' => __('mycpt', 'synTh_textDomain'),
        'singular_name' => __('mycpt', 'synTh_textDomain')
        );

        $args = array(
        'labels' => $labels,
        'public' => true,
        'has_archive' => true,
        'publicly_queryable' => true,
        'exclude_from_search' => false,
        'show_ui' => true,
        'show_in_menu' => true,
        'has_archive' => true,
        'query_var' => true,
        'rewrite' => array('slug' => 'boom'),
        'supports' =>array('title','editor', 'custom-fields','thumbnail')
        );  

        register_post_type( 'mycpt', $args );
    }

everything works as expected. There is an archive-boom.php, which I can access via: www.domain.com/boom/

I flushed the permalinks settings and I have them set to postname.

Is there a difference, when attaching to a hook from inside a class??

1 Answer 1

1

You only create an instance of your class on admin requests, so your CPT doesn't exist on front end requests. Instead of:

if( is_admin() )
    $cpt = new CPT('cpt_child');

create the instance on all requests:

$cpt = new CPT('cpt_child');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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