简体   繁体   中英

Custom code to drive pages with the same name as custom post types in wordpress

If I create pages, I can create custom template php files to drive them. eg, the page "Villages" I can drive with "page-villages.php instead of its default "page.php"

However. If I have a custom post type named "town" and I try to create a page with the name "Towns", I can't seem to be able to have a php file named "page-towns.php" to drive it, it always defaults "index.php"

It may have to do with the registering?

  register_post_type('town', array(  /* by default, the post type name is the SLUG for that post type*/
    'public' => true, /* makes post type visible to admins, editors, etc*/
    'supports' => array('title', 'editor', 'thumbnail', 'excerpt', 'custom-fields'),
    'has_archive' => true, /* make post type have a archive URL */
    'rewrite' => array('slug' => 'towns'), /*plural name for the SLUG instead of default singular name */
    'labels' => array(
      'name' => 'Towns',
      'add_new_item' => 'Add New Town',
      'edit_item' => 'Edit Town',
      'all_items' => 'All Towns',
      'singular_name' => 'Town'
    ),
    'menu_icon' => 'dashicons-admin-multisite'
  ));

Is there a way around this?

You're looking for the single-{post}.php template file .

If the file single.php exists, Wordpress will use that when viewing a single post. Custom post types will use that file too. If you want to override it, use single-{your-post-name}.php

In your case you'd use single-towns.php

-

Also, I believe you should name custom post types with a singular name, so perhaps update to using town as your post name, then you'd use single-town.php as your template file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM