0

I am stumped on a bit of php code in my template.

I have a custom field named "services" with a value such as "2402, 2366, 78" These are page ID's.

In my template I want to do the following: Get any children of page ID 2526. Then get the value of that custom field for each of the children. Then get the ID of the current page the template is being used for ( get_the_ID() ). Then create an IF statement. IF a number in the value matches the number of the page ID, echo something and wrap the echoed text with a link back to the child page of ID 2526, whose custom field has value that matches the current page ID.

I can also enter the values as 2402 2366 78 if its easier without commas.

This is where I am so far:

<?php
$currentPageID = get_the_ID();
$child_pages = $wpdb->get_results("SELECT *    FROM $wpdb->posts WHERE post_parent = 2526 AND post_type = 'page' ORDER BY menu_order", 'OBJECT');
if ( $child_pages ) : foreach ( $child_pages as $pageChild ) : setup_postdata( $pageChild );
$services = get_post_meta( $pageChild->ID, 'services', true );
if (preg_match('/(^|,)'.$currentPageID.'($|,)/', $services)){
    echo "matches";
} 
else {
    echo "does not match";
}
endforeach; endif;
?>

I don't get any errors, but nothing shows up either. I also am not sure how to add the link for the related child page.

Thanks for any help in advance!

0

Here is the code that ended up working for me:

<?php
  $mypages = get_pages( array( 'child_of' => $post->ID, 'sort_column' => 'menu_order', 'sort_order' => 'asc' ) );
  foreach( $mypages as $page ) {         
  $content = $page->post_content;
  $content = apply_filters( 'the_content', $content );
  $price = get_post_meta( $page->ID, 'price', true );
?>
<div class="service">
<h4><a href="<?php echo get_page_link( $page->ID ); ?>"><?php echo $page->post_title; ?></a></h4>
<div class="price"><?php echo $price; ?></div>
<p><?php echo $content; ?></p>
<p><?php
      $currentPageID = $page->ID;
  $child_pages = $wpdb->get_results("SELECT *    FROM $wpdb->posts WHERE post_parent =2526 AND post_type = 'page' ORDER BY menu_order", 'OBJECT');
  if ( $child_pages ) : foreach ( $child_pages as $pageChild ) : setup_postdata( $pageChild );
  $services = get_post_meta( $pageChild->ID, 'services', true );
      if (preg_match('/(^|,| )'.$currentPageID.'($|,| )/', $services, $matches)){
  echo "<a class='promotion-link' href='" . get_permalink('2526') . "'>A promotion is available for this service</a><br/>" ;
  //  echo "matches";
}
endforeach; endif;
?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.