Friday, 6 September 2013

Wordpress content displaying weird when using foreach

Wordpress content displaying weird when using foreach

I am currently doing some custom work on a clients wordpress site. I am
using the code below to query the database which works fine. However, when
i try showing the results it isnt working as it should. Basically i am
trying to query the postmeta table to find info from a custom field i
added, which in this case might be my name, andy. Once the system finds
all the posts with the custom field value as andy, it should then use the
id for those rows and display the title, content and date for each one.
This was working fine until i viewed the page live and basically it is
counting the amount of times my name appears, and echoing info from all of
the rows, whereas i want it to only echo info from the rows that are
publish. Can any one help, huge headache for me!:
PHP
<?php
require_once('dbConfig.php');
// This variable grabs the name in the URL
$r = get_permalink();
$r = explode('/', $r);
$r = array_filter($r);
$r = array_merge($r, array()); //reset keys
$code = $r[3];
$getName = preg_replace("/[^a-zA-Z0-9\s]/", "", $code);
$name = $db->real_escape_string($getName);
?>
<?php
$allposts = $wpdb->get_results( $wpdb->prepare("SELECT post_id
FROM $wpdb->postmeta WHERE meta_value = %s", $name) );
foreach ($allposts as $singlepost) {
$wpPosts = $wpdb->get_row( $wpdb->prepare("SELECT post_title,
post_content, post_date_gmt FROM $wpdb->posts WHERE ID = %d
AND post_status = 'publish' AND post_type='post' ORDER BY ID
DESC", $singlepost->post_id) );
$wpPostsDate = new DateTime($wpPosts->post_date_gmt);
echo '<h1>'.$wpPosts->post_title.'</h1><br>';
echo 'Post Content: '.$wpPosts->post_content.'<br>';
echo 'Post Date: '.$wpPostsDate->format('jS F Y').'<br><br>';
}
?>

No comments:

Post a Comment