liam
Home // Get the post ID by searching a post title from a post_type

Get the post ID by searching a post title from a post_type

Posted on

Getting the post id for a specific post has helped me out when I need to get the ID from a post in another post type.

Useful for when you need information from another post type for a specific customer using get_post_meta. You can also search by get_post_meta();.


$post_type = 'customer'; // the post type you want to search in
$searchFor = 'John D' // the title of the post title can also be numbers

$args = array(
		'post_type'      => $post_type,
		'post_status'    => array('publish', 'private'),
		'fields'         => 'ids',
		'title'          => $searchFor
);

$matching_St = get_posts($args);
if ($matching_St) {
		$thePostID = $matching_St[0]; // the $thePostID will store the post ID
}

								

Search by get_post_meta();

You see I’ve used $wcid. This is the post ID from the post in the current post type so for example if you’re in “warehouse” and you need some information from the “customer” post type, you can use the code below.

$post_type = 'customer'; // the post type you want to search in
$searchFor = get_post_meta($wcid, 'custName', true); // using get_post_meta

$args = array(
		'post_type'      => $post_type,
		'post_status'    => array('publish', 'private'),
		'fields'         => 'ids',
		'title'          => $searchFor
);

$matching_St = get_posts($args);
if ($matching_St) {
		$thePostID = $matching_St[0]; // the $thePostID will store the post ID
}

Another way I’ve found useful is the following code below.

In summary, this code aims to find a warehouse post that corresponds to a given client order number. It searches for warehouse posts with the specified cwOrderNumber custom field value, and if found, returns the ID.

$post_type = 'whouse';
$wID = get_post_meta($theid, 'cOrderNumber', true);

$args = array(
		'post_type' => $post_type,
		'post_status' => array('publish', 'private'),
		'fields' => 'ids',
		'meta_query' => array(
				array(
						'key' => 'cwOrderNumber', // the key for warehouse order numbers
						'value' => $wID, // find it by using the cOrderNumber 
						'compare' => '=', // exactly equal = exact match
						),
			),
);

$matching_warehouses = get_posts($args);
if ($matching_warehouses) {
		$warehouse_id = $matching_warehouses[0];
}

I hope you find the following code helpful and if so, feel free to use it in your WordPress developments.

liam