Dev Notes

Various Cheat Sheets and Resources by David Egan/Carawebs.

WordPress Pages for Posts - Show the Content Editor


WordPress
David Egan

When WordPress has a static front page (as set in “Settings” > “Reading”), it is often useful to display introductory content on the page that has been selected for posts.

The posts page is determined by the ‘page_for_posts’ value in the ‘option_name’ column in the WordPress options table. The ID of this page can be retrieved by:

<?php
$page_for_posts_ID = get_option( 'page_for_posts');

This allows the page content and featured image to be displayed in the template.

Display Page Content

By default, the page for posts uses the WordPress home.php template. To access the page content in this template:

<?php
$posts_page = get_post( get_option( 'page_for_posts' ) );
echo apply_filters( 'the_content', $posts_page->post_content );

Where the Hell is the Editor?

WordPress (as of version 4.5.1 anyway) has an extremely annoying characteristic whereby the content editor is not shown on the page for posts if the post_content field is empty. Instead, you get an annoying message telling you what you already know - that this is the page selected to display blog posts.

There are two fixes:

  1. Temporarily set a different page for blog posts, add some content to your original posts page, and then switch the setting back to the original posts page
  2. Remove the annoying message and add back the editor by hooking onto edit_form_after_title

When I first noticed this, it bugged the hell out of me - since my development site had page content, the editor displayed normally (not so in the staging site).

The culprit is this little diamond in /wp-admin/edit-form-advanced.php:

<?php
if ( $post_ID == get_option( 'page_for_posts' ) && empty( $post->post_content ) ) {
	add_action( 'edit_form_after_title', '_wp_posts_page_notice' );
	remove_post_type_support( $post_type, 'editor' );
}

The second, less hackish fix:

<?php
/**
 * Add the wp-editor back into WordPress after it was removed in 4.2.2.
 *
 * @see https://wordpress.org/support/topic/you-are-currently-editing-the-page-that-shows-your-latest-posts?replies=3#post-7130021
 * @param $post
 * @return void
 */
 function fix_no_editor_on_posts_page($post) {

   if( $post->ID != get_option( 'page_for_posts' ) ) { return; }

   remove_action( 'edit_form_after_title', '_wp_posts_page_notice' );
   add_post_type_support( 'page', 'editor' );

 }

 // This is applied in a namespaced file - so amend this if you're not namespacing
 add_action( 'edit_form_after_title', __NAMESPACE__ . '\\fix_no_editor_on_posts_page', 0 );

Credit for this goes to crgeary

I can’t imagine why this “functionality” has been built in. It would surely be better for WP core to be less opinionated - but at least it’s fairly easy to undo the damage.

References


comments powered by Disqus