Skip to content

Instantly share code, notes, and snippets.

@elvismdev
Created January 28, 2019 11:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elvismdev/fde79d023f50ae3a58a3a20c340aea6f to your computer and use it in GitHub Desktop.
Save elvismdev/fde79d023f50ae3a58a3a20c340aea6f to your computer and use it in GitHub Desktop.
Relates a post by title.
<?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