WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm trying to write a function that will "pair" my custom post type with a page with the same name as the custom post type.

The aim is that when a custom post type is saved, it checks if there's a page with the same name as the custom post type post, and if so, it pulls the id from that page and puts it as the parent id for the CPT post. It's a hacky way for me to keep a bond between them (the custom post type posts inherits different values from the page).

However, I can't get it to work, it drops me an id, but it's the wrong id (it grabs the id of the page with the highest id), not sure what I'm doing wrong.

Here's the current code:

function find_parent_for_cpt( $data , $postarr ) {
    global $post;
    if ($post->post_type != 'post' || 'page'){
        $post_type = $post->post_type;

        $mypages = get_pages();
        foreach($mypages as $page){     
            if($page->post_title==$post_type) {
                $data[ 'post_parent' ] = $page->ID;
                return $data;
add_filter( 'wp_insert_post_data' , 'find_parent_for_cpt' , '99', 2 );
share|improve this question
up vote 1 down vote accepted

You have a few issues in your function. first, $data contains the post type, so we look there. your if statement won't work like that, you have to check conditions individually. and to find the matching page, just query by title for your page with WP_Query:

function find_parent_for_cpt( $data ) {
    if ( $data['post_type'] != 'post' && $data['post_type'] != 'page' ):
        $args = array(
            'name' => $data['post_type'],
            'post_type' => array( 'page' )
        $match = new WP_Query( $args );
        if( $match->post_count == 1 )
            $data[ 'post_parent' ] = $match->post->ID;
    return $data;
add_filter( 'wp_insert_post_data' , 'find_parent_for_cpt' , '99', 2 );

also note you have to return the post data whether or not you modify it. another thing you may have issues with is that there are other post types types beside post and page that are not your custom types, where I assume this action gets fired. it may be best to test explicitly for your custom types to decide whether or not to assign parent.

share|improve this answer
Thanks so much! Works splendid. I want it to work with every CPT created. What more should I exclude to make sure I don't run into problems? – INT Jun 7 '12 at 21:22
@INT - attachment, revision, and nav_menu_item are the other native post types. – Milo Jun 7 '12 at 21:59

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.