0

I've chosen a custom page(-post) to be my front page. Now I want to use a block template only on that page, when editing it in the Gutenberg editor. As I understand it I have to add it on "init" or close to it, before I know the post_ID so I can't do a if ( get_option( 'page_on_front' ) === $post_ID ).

What are my options?

Edit: I've tried this but since is_front_page() is returning 'false' it doesn't work:

function home_block_template() {
    $post_type_object = get_post_type_object( 'post' );

    if ( is_front_page() ) {
        $post_type_object->template = array(
            array( 'core/image', array() ),
        );
    }
}
add_action( 'init', 'home_block_template' );
0

The following code should work for you let me know if you face any problem.

function myplugin_register_template() {
    $post_type_object = get_post_type_object( 'post' );

    if( is_front_page() ) {
        $post_type_object->template = array(
            array( 'core/image' ), // add your core/custom blocks here
        );
    }
}
add_action( 'init', 'myplugin_register_template' );
  • Thanks, but is_front_page() is returning 'false' so it doesn't work. – Richard B Apr 3 '19 at 14:34
  • Is front page is returning false because that page is not your front page. Set that page as your front page by going into WordPress Dashboard > Settings > Reading menu from sidebar. – Mehmood Ahmad Apr 3 '19 at 14:41
  • Well, I wish it was that easy. The page I'm looking at is my chosen front page in the settings, it even says so in the posts list. – Richard B Apr 3 '19 at 14:51
  • May be conditionals are set after init hook therefore it is not working. Can you please use wp hook instead of init and share your findings here. – Mehmood Ahmad Apr 3 '19 at 17:40
  • Already tried the wp hook. I solved it though, just posted the answer. – Richard B Apr 4 '19 at 20:27
0

Setting $post_type_object->template seems to be done on 'init' (or close to it) while is_front_page() is set later, so I had to use $_GET['post'] instead. I also changed get_post_type_object( 'post' ) to 'page'. Like this:

add_action( 'init', 'home_block_template' );
function home_block_template() {
    if ( ! is_admin() || ! isset( $_GET['post'] ) || get_option( 'page_on_front' ) !== $_GET['post'] ) {
        return false;
    }

    $post_type_object = get_post_type_object( 'page' );
    $post_type_object->template = array(
        array( 'core/list' ),
    );
}

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.