最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

posts - WordPress automatic and permanent page

programmeradmin0浏览0评论

When WordPress setup is complete, I want a page such as "localhost/contact" to occur automatically and make it permanent. In short, it cannot be edited and deleted in the panel. It should even be invisible on the panel. But just like WordPress should have a place in the normal ID system.

Is this technically possible?

When WordPress setup is complete, I want a page such as "localhost/contact" to occur automatically and make it permanent. In short, it cannot be edited and deleted in the panel. It should even be invisible on the panel. But just like WordPress should have a place in the normal ID system.

Is this technically possible?

Share Improve this question asked Oct 6, 2019 at 9:59 BOZBOZ 3201 silver badge7 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 3

Yes, that is doable.

I don't know about running scripts immediately after WP installation is complete, but you could implement your idea perhaps with a must-use plugin.

First you probably want some kind of way to get the contact page id. A helper function for that,

function get_my_contact_page_id() {
  return get_option( 'my_contact_page', 0 ); // custom option might be a logical place to store the id
}

Then pick your favorite hook that you'll use to check, if the contact page needs to be created. For example run the check only when the theme is changed.

function create_contact_page(){
  if ( ! get_my_contact_page_id() ) {
    $args = array(
      'post_type'   => 'page',
      'post_status' => 'publish',
      'post_title'  => __( 'Contact', 'textdomain' ),
      //'post_name'   => 'contact', // add this, if you want to force the page slug
    );
    $id = wp_insert_post( $args );
    if ( $id ) {
      add_option('my_contact_page', $id); // custom option might be a logical place to store the id
    }
  }
}
add_action( 'after_switch_theme', 'create_contact_page' );

To exclude the page from the Pages admin view, use pre_get_posts.

function exclude_single_page_on_admin_page_list($query) {
  if ( is_admin() ) {
    global $pagenow;
    if ( 'edit.php' === $pagenow && 'page' === $query->query['post_type'] ) {
      if ($contact_page = get_my_contact_page_id()) {
        $query->set( 'post__not_in', array( $contact_page ) );
      }
    }
  }
}
add_action( 'pre_get_posts', 'exclude_single_page_on_admin_page_list' );

To prevent anyone accessing the contact page editing view directly, add a redirect protection.

function prevent_excluded_page_editing() {
  global $pagenow;
  if ( 'post.php' === $pagenow && isset( $_GET['post'] ) && $_GET['post'] == get_my_contact_page_id() ) {
    wp_redirect( admin_url( '/edit.php?post_type=page' ) );
    exit;
  }
}
add_action( 'admin_init', 'prevent_excluded_page_editing' );
发布评论

评论列表(0)

  1. 暂无评论