0

I am creating a custom page template:

< ?php
/*
 * Template Name: sliding content
 * Description: Sliding category contents
*/
get_header(); ?>

<div id="primary" class="content-area">
    <main id="main" class="site-main" role="main">
                        <?php while ( have_posts() ) : the_post(); ?>
                                <div class="post">
                                    <h2 id="post-<?php the_ID(); ?>"><?php the_title();?></h2>
                                    <div id="accordion">
                                        <?php the_content();?>
                                    </div>
                                </div>
                        <?php endwhile; // end of the loop. ?>

    </main><!-- #main -->
</div><!-- #primary -->
< ? php get_footer(); ?>

I would like to have predefined text, that will be displayed in wp-admin page's editor once this template is chosen. The admin will be able to just modify; something like this will be in the editor:

<h1>modify this header for title</h1>
<div id="accordion">
 write your content here
</div>

What is the wordpress way of achieving this task?

1

The code below will work, read inline comments. Paste it into your theme functions.php or plugin.

The only problem with this is the it will only work when the template is selected and the post is saved/updated and the editor is blank.

<?php

function wpse_177576_update_editor_content( $post_id ) {

    if ( wp_is_post_revision( $post_id ) )
        return;

    $post = get_post( $post_id );
    $content = apply_filters( 'the_content', $post->post_content );

    if ( '' != $content )
        return; // content already exists, we don't want to overwrite it.

    $template = get_post_meta( $post_id, '_wp_page_template', true ); // Returns the template file name i.e. page-accordion.php

    if ( $template == 'page-accordion.php' ) { // change "page-accordion.php" to the filename of your template
        $content = '<h1>modify this header for title</h1>
                    <div id="accordion">
                        write you content here
                    </div>';
    }

    /**
     * Update the post with template content
     */
    wp_update_post( array(
        'ID' => $post_id,
        'post_content' => $content
    ) );
}
add_action( 'save_post', 'wpse_177576_update_editor_content' );

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.