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

plugin development - How to create a page with a form programmatically in WP?

programmeradmin1浏览0评论

I made some research and found a way how to create custom pages using content (post) types. However, I do not want to create a new post type, I just want to create a page having a certain URL (/form) with a form on it. I was not able to find how to do it without custom post types. Can someone show me the correct direction? Thanks a lot.

I made some research and found a way how to create custom pages using content (post) types. However, I do not want to create a new post type, I just want to create a page having a certain URL (/form) with a form on it. I was not able to find how to do it without custom post types. Can someone show me the correct direction? Thanks a lot.

Share Improve this question asked May 21, 2019 at 15:26 petiarpetiar 1211 silver badge5 bronze badges 3
  • 2 I'm not sure I understand. Why can't you just go to Pages > Add New, create a page called "Form" and put your form on it? If you needs something more than that you'll need to be more specific with your question. – Jacob Peattie Commented May 21, 2019 at 15:36
  • Because I want to do it programmatically. It's in the title. I do not need to explain why do I need to do it that way. – petiar Commented May 22, 2019 at 15:49
  • Can someone clear up what is wrong with this question? It is perfectly clear what I want to achieve (create a page programmatically, not via admin interface, obviously - it's right in the title!) and I also made my effort to try to find it out, however, no luck. An accepted answer bellow proves that the question is perfectly alright. Obviously, most of the WP "developers" just know how to click mouse and install plugins. – petiar Commented May 22, 2019 at 21:15
Add a comment  | 

2 Answers 2

Reset to default 3

You can use wp_insert_post() function with 'after_theme_setup' action hook to programatically create pages. Here is a short example,

add_action( 'after_setup_theme', 'create_form_page' );
function create_form_page(){

    $title = 'Form';
    $slug = 'form';
    $page_content = ''; // your page content here
    $post_type = 'page';

    $page_args = array(
        'post_type' => $post_type,
        'post_title' => $title,
        'post_content' => $page_content,
        'post_status' => 'publish',
        'post_author' => 1,
        'post_slug' => $slug
    );

    if(post_exists($title) === 0){
        $page_id = wp_insert_post($page_args);
    }

}   

Install a form plugin. Contact form 7 is a good one : https://en-au.wordpress/plugins/contact-form-7/

Create a form using the plugin.

Create a normal WP page and add your form to it by pasting the contact-form-7 shortcode into the page.

发布评论

评论列表(0)

  1. 暂无评论