Created
January 28, 2019 11:05
-
-
Save elvismdev/fde79d023f50ae3a58a3a20c340aea6f to your computer and use it in GitHub Desktop.
Relates a post by title.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Relates a post by title. | |
function rel_post_by_title( $title, $post_type ) { | |
// If we don't have a title to lookup, then return null; | |
if ( !$title ) return null; | |
// Check if related post already exists. If it doesn't then create it. | |
// Attempt to find page by value. | |
$page = get_page_by_title( $title, null, $post_type ); | |
// Check if we have a match | |
if ( isset( $page->post_title ) && $page->post_title === $title ) { | |
$post_id = $page->ID; | |
} else { | |
// Create post | |
$args = array( | |
'post_status' => 'publish', | |
'post_type' => $post_type, | |
'post_title' => $title | |
); | |
$post_id = wp_insert_post( $args ); | |
} | |
// Check if we have page ID to save, return it. | |
if ( $post_id ) { | |
return $post_id; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment