WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] How to check if a Post Id exists? (3 posts)

  1. temporaneoit
    Member
    Posted 4 years ago #

    Hi all and thank you in advance.

    The problem: I do not know how to check if a Post Id exists.

    I wrote some code inside "single.php" to show "related posts" based upon "custom values" (the id's separated by "|") in a "custom field".

    The id's are not checked in the "Edit Post" page; it is only a string like this "12|44|67", freely written by me. I parse the string to obtain the single components - for example "12" "44" "67".

    Before printing the list of related posts by a loop, I have to check if those id's exist.

    The code in the following:

    $ids_related_arr=get_post_custom_values('ids_related'); // ids_related contains for examples 12|44|67
    if(isset($ids_related_arr)){
    	foreach($ids_related_arr as $key=>$value){
    		$ids_arr=explode('|',$value);
    		foreach($ids_arr as $key_id=>$value_id){
    			if(/* the Post with Id=$value_id exists */){
    				// write the link to the post
    			};
    		};
    	};
    };
  2. alchymyth
    Forum Moderator
    Posted 4 years ago #

    this might work:

    foreach($ids_arr as $key_id=>$value_id){
       $rel_post_id = $key_id=>$value_id;
       $rel_post = get_posts('p='.$rel_post_id) ;
       if($rel_post) {
          // write the link to the post
       };
    };
  3. temporaneoit
    Member
    Posted 4 years ago #

    Dear alchymyth,
    thank you very much!

    I had only to change
    $rel_post_id = $key_id=>$value_id;
    into
    $rel_post_id = $value_id;

    Than you again.

Topic Closed

This topic has been closed to new replies.

About this Topic