Check Post Title is Unique Do While Loop

Hi all,

I’ve tried registering but I haven’t received any activation emails yet so I thought I’d just post this and see if I can get help regardless.

I know this is a Wordpress sounding issue but the basic problem is PHP so I would really appreciate the help.

I’m trying to make a seemingly simple bit of php (it output’s to a Gravity Forms field, but that’s basically irrelevant).

I’m using Gravity Forms to create posts, which I can do easily, however I want each post to have a unique title (as this is how the user navigates).

I managed to get this working for registration by checking if the user registration id (also the post title in that situation) was already in use, like so:
[php]
// Builds complete user id function build_id ($pcode_id, $assigned_id_no) {

do {
$cmplt_id = $pcode_id . “-” . number_pad($assigned_id_no, 3); // Gets postcode string and calls the number padding function to add the leading 0’s
$assigned_id_no++; // Increase assigned_id_no
}
while(username_exists($cmplt_id)); // Restart loop if username_exists is true
return $cmplt_id;

return $cmplt_id;
}

// Takes a string and add’s however many 0’s (or other character placed there) to the left of the string
function number_pad($number,$n) { return str_pad((int) $number,$n,“0”,STR_PAD_LEFT);
}
[/php]

$pcode_id is just a formatted post code as a string and $assigned_id_no is simply a loop number, passes 1 basically.

As you can see the while criteria is does this exist, but for the life of me I can’t emulate this by simply checking post type.

The nearest I’ve come is get_page_by_title() and if it’s null then finish else loop, but it doesn’t work:

[php]
function home_patient_id() { $post_id = $_GET[‘home_id’]; $home_post_code = get_post_meta($post_id, “wpcf-home-post-code”, true); $home_post_code = format_id($home_post_code); $home_post_code = build_home_id($home_post_code, 1);

return $home_post_code;
}

// Builds complete user id function build_home_id ($pcode_id, $assigned_id_no) {

do {
$cmplt_id = $pcode_id . “-” . number_pad($assigned_id_no, 3); // Gets postcode string and calls the number padding function to add the leading 0’s
$assigned_id_no++; // Increase assigned_id_no
$exist = get_page_by_title($cmplt_id);
}
while(get_page_by_title($cmplt_id)); // Restart loop if username_exists is true
return $cmplt_id;

return $cmplt_id;
}
[/php]
I’ve also tried checking if it returns null but nothing is working, I either get nothing or an infinite loop.

Can someone please help I’m pulling my hair out over this!

Many thanks.

Hi,

First of all, delete one of the return $cmplt_id; you only need one.

You have 2 sets of php codes but i see both of them are doing pretty much the same thing. Can you explain in more detail? Also, what is the actual problem that you are facing? I can’t understand what is your problem maybe you can elaborate more?

You didn’t provide the function body of username_exists and get_page_by_title there might be some problem inside it.

Regards,
developer.dex2908

Sorry bud I copied the question over from the wordpress.org forums where it’s gone unanswered for a week now.

Let me go over it in more detail.

I am using Gravity Forms to register posts in various custom post types. The custom post type “Patient” is being used in two ways. The first code block (which I’ll repost and make sure is clean this time!) is used when a user registers themselves as a patient and it takes their post code from the first page of the form, formats it and adds a suffix to it giving it the form “AB12CD-001” and then outputs it in a read-only field on the second page. This code works perfectly.

[php]
add_filter(‘gform_validation_1’, ‘make_user_id’); //Builds the patient id

function make_user_id($validation_result) {

// Get the form object from the validation result
$form = $validation_result["form"];

// Get the current page being validated
$current_page = rgpost('gform_source_page_number_' . $form['id']) ? rgpost('gform_source_page_number_' . $form['id']) : 1;

// Loop through the form fields
foreach($form['fields'] as &$field){

    // If the field does not have our designated CSS class, skip it
    if(strpos($field['cssClass'], 'postcode') === false)
        continue;

    // Get the field's page number
    $field_page = $field['pageNumber'];

    // Check if the field is hidden by GF conditional logic
    $is_hidden = RGFormsModel::is_field_hidden($form, $field, array());

    // If the field is not on the current page OR if the field is hidden, skip it
    if($field_page != $current_page || $is_hidden)
        continue;

    // Get the submitted value from the $_POST
	$field_value = rgpost("input_2_5");		// Specified field
	$field_value = format_id($field_value);
				
	$user_id = build_id($field_value, 1);  // Call build_id to assemble the user_id
		

	foreach($form['fields'] as &$field2){
		if(strpos($field2['cssClass'], 'userid') === false) // Loop through fields again to find the "User ID" field
			 // Loop through fields again to find the "User ID" field
        continue;
		
		$field2["defaultValue"] = $user_id; // Add completed user id as default value to "User ID" field

}}
$validation_result[‘form’] = $form; // Manipulate $validation_result with modified $form

// Return the validation result
return $validation_result;

}

//Formats the post code into the user id
function format_id ($post_code) {
$post_code = preg_replace(’/\s+/’, ‘’, $post_code); // Remove spaces and any character that isn’t a number or letter
$post_code = strtoupper($post_code); // Convert to uppercase
return $post_code;
}

// Builds complete user id
function build_id ($pcode_id, $assigned_id_no) {

 do {
        $cmplt_id = $pcode_id . "-" . number_pad($assigned_id_no, 3);  // Gets postcode string and calls the number padding function to add the leading 0's
         $assigned_id_no++;	// Increase assigned_id_no
    }
    while(username_exists($cmplt_id));	// Restart loop if username_exists is true
    return $cmplt_id;
		 
return $cmplt_id;

}

// Takes a string and add’s however many 0’s (or other character placed there) to the left of the string
function number_pad($number,$n) {
return str_pad((int) $number,$n,“0”,STR_PAD_LEFT);
}
[/php]

As you can see the code will build the user id from the post code and then use the Wordpress function “username_exists()” to check the string against existing user id’s. If it finds the built id is already in use it loops to increase the suffix number by one resulting in “AB12CD-002” and then it checks again and this continues until it makes a user id that is not in use.

As I’ve said this works perfectly.

My problem is that I’m trying to replicate this functionality with two minor differences.

Care homes have patients that need to be stored in the Patient custom post type also, but they do not require login details as they will not be using the site themselves, the home management will be. So the site needs to get the homes post code via:

[php]
$post_id = $_GET[‘home_id’];
$home_post_code = get_post_meta($post_id, “wpcf-home-post-code”, true);
[/php]

Then comes my BIG problem, I need built id to test against existing post titles within the custom post type patient. So I believe I need to use a similar loop criteria so it can test the created string against post titles but I just cannot figure out how to achieve this. From what I’ve read the Wordpress function get_page_by_title() should be able to return post titles but I just can’t seem to use it correctly.

Any criteria I attempt either results in the same user id being out every time or an infinite loop winding up in the php 30 second time out error.

You’re the first person I’ve had reply about this, I really appreciate your help on this bud, I’ve been trying to crack this for over a week now and I’m sure it should be easier than this.

Hi,

It seems that your code. Is very specific to wordpress. I’m not a wordpress developer, so unless its general enough, I’m afraid i’ll be of no help to you.

If i were you, i’ll definitely check if get_page_by_title is returning the value that you were expecting. Do a var_dump to check the returned value.

Good luck!

Regards,
developer.dex2908

Thanks for the input, honestly I don’t know how to use var dump with Wordpress so I can’t post the output.

If you assume it’s all php, ignoring the Wordpress bits, if you assume that the database field is called “post_title”, how would you go about dealing with the loop. I’m really desperate for a break through on this and I can find no Wordpress functions for this issue so how would you deal with it as php?

Thanks bud.

Hi,

[php]
do {
$cmplt_id = $pcode_id . “-” . number_pad($assigned_id_no, 3); // Gets postcode string and calls the number padding function to add the leading 0’s
$assigned_id_no++; // Increase assigned_id_no
$exist = get_page_by_title($cmplt_id);
var_dump(get_page_by_title($cmplt_id));
die();
}
while(get_page_by_title($cmplt_id)); // Restart loop if username_exists is true
return $cmplt_id;
[/php]

I dunno if it helps but if you inlcude those 2 lines, var_dump(get_page_by_title($cmplt_id)); and die(); you would be able to see what is being returned by get_page_by_title function. You can then decide if it returns the value that you were expecting.

Regards,
developer.dex2908

That’s great! Thanks for that, I feel like I’m finally getting somewhere here.

I think the problem here is that “get_page_by_title()” returns an object or null so that’s why it won’t validate straight away.

If I dump the basic return I get this:

object(stdClass)#533 (25) { ["ID"]=> int(430) ["post_author"]=> string(1) "1" ["post_date"]=> string(19) "2012-08-23 15:22:11" ["post_date_gmt"]=> string(19) "2012-08-23 14:22:11" ["post_content"]=> string(0) "" ["post_title"]=> string(10) "MO05ID-001" ["post_excerpt"]=> string(0) "" ["post_status"]=> string(7) "publish" ["comment_status"]=> string(6) "closed" ["ping_status"]=> string(6) "closed" ["post_password"]=> string(0) "" ["post_name"]=> string(10) "mo05id-001" ["to_ping"]=> string(0) "" ["pinged"]=> string(0) "" ["post_modified"]=> string(19) "2012-08-23 15:22:11" ["post_modified_gmt"]=> string(19) "2012-08-23 14:22:11" ["post_content_filtered"]=> string(0) "" ["post_parent"]=> int(0) ["guid"]=> string(62) "http://localhost/wordpress/patient/mo05id-001" ["menu_order"]=> int(0) ["post_type"]=> string(7) "patient" ["post_mime_type"]=> string(0) "" ["comment_count"]=> string(1) "0" ["ancestors"]=> array(0) { } ["filter"]=> string(3) "raw" }

If I then specify a part to return like this:

[php]
function build_home_id ($pcode_id, $assigned_id_no) {

$cmplt_id = $pcode_id . “-” . number_pad($assigned_id_no, 3); // Gets postcode string and calls the number padding function to add the leading 0’s
$existing = get_page_by_title($cmplt_id, OBJECT, “patient”);
$existing_post = $existing->post_title;
var_dump($existing_post);
die();
[/php]

I get this:

string(10) "MO05ID-001"

Now if I can remove the extra bits of that string to just be left with MO05ID-001 I could then use something like this as the loop criteria couldn’t I?

[php]
while($posttitle != $cmplt_id)
[/php]

Does that make sense from a PHP perspective bud?

Once again thanks so much for the help!

Hi,

when you say remove the extra bits of string, did you mean the bolded characters? string(10) "MO05ID-001"? If you are, don’t worry its because of the var_dump. Its showing you that it is a string with 10 characters that’s all.

since you have assigned $existing->post_title to $existing_post, i think

while($existing_post != $cmplt_id) would be fine

Good luck bud!

Regards,
developer.dex2908

Ok 98% success!

This code is working and posting the next increment for the post number:

[php]
function build_home_id ($pcode_id, $assigned_id_no) {
do {
$cmplt_id = $pcode_id . “-” . number_pad($assigned_id_no, 3); // Gets postcode string and calls the number padding function to add the
$assigned_id_no++; // Increase assigned_id_no
$existing = get_page_by_title($cmplt_id, OBJECT, “patient”);
$existing_post = $existing->post_title;

}
while($cmplt_id == $existing_post); // Restart loop if the built id matches any already in existance
return $cmplt_id;

[/php]

The only problem is that it’s giving this error:

Notice: Trying to get property of non-object in C:\xampp\htdocs\wordpress\wp-content\themes\MyTheme\functions\homepatientregistration.php on line 44

Notice: Trying to get property of non-object in C:\xampp\htdocs\wordpress\wp-content\themes\MyTheme\functions\homepatientregistration.php on line 44

Line 44 is this:

$existing_post = $existing->post_title;

But I think this is because I’m using the “OBJECT” variable in the preceding line:

$existing = get_page_by_title($cmplt_id, OBJECT, "patient");

I know this is heavily Wordpress but I thought at least you could help me understand the error it’s generating. Obviously it’s not critical as the code is working but I don’t want to have any errors at all if it’s possible.

Thanks for this dude you’ve given me the nudge I needed to get this working!

You’ve been great, if we can just solve this last issue then this is fully working.

Hi,

I think i know what is the problem. You see, when you reach a second or more cycle or your while loop,

your $cmplt_id will sure be non exising in the database right? so when the following line is executed,
$existing = get_page_by_title($cmplt_id, OBJECT, “patient”); will return null so then the next line:
$existing_post = $existing->post_title; you are trying to access the property post_title but currenty $existing is not an object but its null. You get what i mean?

Regards,
developer.dex2908

I’m with you, so that just means it’s an unavoidable, harmless error that (well notice, as it clearly states) and I can just ignore it?

That’s cool, as long as it’s safe and I can just turn the debugging off when I’m done and it’ll just disappear into the background.

Cool.

You’ve been amazing bud, providing I’m right about what you are saying here that’s great.

Thank you SO much bud, I couldn’t have done it without you!

Hi,

It can be avoided. All you need to do is this:

if(is_object($existing))
$existing_post = $existing->post_title;

Hey if you have any friends that wants to get started with php, recommend my site will ya?

Regards,
developer.dex2908

Sorted, 100% working!

Thank you so much for your help, I would never have thought to check if the object existed or not but once it’s pointed out to you it’s kinda obvious ain’t it :smiley:

I’ve been learning as I’ve been going with this site and PHP is very friendly most of the time but trying to integrate basic mods with higher end stuff like Wordpress and it’s various plugins has presented quite a challenge at times. So thanks for teaching me some more very useful stuff.

I will most definitely pass on your site, my brother is a first year student who is doing some PHP soon so I’ll let him and his class know.

Once again thanks for everything, I couldn’t have done it without you bud.

Sponsor our Newsletter | Privacy Policy | Terms of Service