Grow your CSS skills. Land your dream job.

Insert corresponding page with every new post [WordPress]

  • # February 5, 2013 at 8:49 am

    I have a custom post type which is used to add sections to a front page, for example ‘PHP section with brief description of PHP’.
    In these sections will be a link to a page which expands on the brief description given in the post (not a link to the post).
    I want to take away the responsibility of the user adding the corresponding page manually by inserting code which will check if a new post of ‘custom_post_type’ is being inserted and add a page of the same name, with default content ready for the user to edit.

    I can’t find the function in the WP core which adds the post.

    Can anyone offer any help? I assume it is the wp_write_post function in wp-admin/post.php called by write_post() in the same script, but I’ve tried a couple of things.
    1. Inserting a wp_insert_post() to insert the corresponding page (didn’t work)
    2. Commenting out wp_write_post() to break the application when a post is added, however the post was still added when this was the case which left me perplexed!

    Any suggestions on where to insert the code or another way of doing it?

    # February 6, 2013 at 7:04 am

    As usual, I’ve missed the point completely with WordPress when setting out to complete a task and have found instead of diving into the core there is a better way of doing it.

    I have attempted all morning to untangle the functionality of post.php and related scripts but then had a brain wave and realised using a simple hook worked much more efficiently.

    Below is the code inserted into the functions.php of my theme.

    class np_service {
    function add_page($post_id) {
    $post = get_post($post_id);

    // Create post object
    $my_post = array(
    ‘post_title’ => $post->post_title,
    ‘post_name’ => $post->post_name,
    ‘post_content’ => $post->post_content,
    ‘post_status’ => ‘publish’,
    ‘post_type’ => ‘page’
    );

    // Insert the post into the database
    wp_insert_post( $my_post );
    }
    }

    add_action(‘publish_{custom_post_type}’, array(‘np_service’, ‘add_page’));

    # February 6, 2013 at 1:13 pm

    Perfect, nice one.

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".