I've got a little sidebar that displaying in the code before the main page content. I wrote this (janky) function to pull in recent posts and comments. Works great, however, its screwing with all my pages and putting posts on all of them. How do I reset/rewind the query or make a new one so all my pages display the correct content?
<?php rewind_posts(); ?>and<?php wp_reset_query(); ?> arent doing the trick for me
Here is my query:
$comments = get_comments('number=10');
$posts = get_posts('posts_per_page=10&category=6');
$most_recent = array();
foreach ($comments as $comment)
$most_recent[strtotime($comment->comment_date_gmt)] = $comment;
foreach ($posts as $post)
$most_recent[strtotime($post->post_date_gmt)] = $post;
unset($comments, $posts);
krsort($most_recent);
$most_recent = array_slice($most_recent, 0, 10);
foreach ($most_recent as $post_or_comment) {
$is_post = isset($post_or_comment->post_date_gmt);
$comment_id = $post_or_comment->comment_ID;
$post_id = $post_or_comment->ID;
$comment_post_id = $post_or_comment->comment_post_ID;
if ($is_post == 1)
{ ?> <li><?php echo $post_or_comment->post_title; ?><span class="tag"><?php echo the_category($post_id); ?></span></li><?php }
else
{ ?><li> <?php echo get_the_title($comment_post_id); ?><span class="tag">Comment</span></li><?php }
// output comments and posts
}
output comments and posts
}
Try using $my_posts and $my_comments instead, just in case WP is using samely-named globals (though I don't think it is).
Also, in your foreach loop, you should only be casting variables when you know the object type, otherwise you're accessing non-existent properties;
foreach ($most_recent as $post_or_comment) {
$is_post = isset($post_or_comment->post_date_gmt);
if ($is_post) {
$post_id = $post_or_comment->ID;
} else {
$comment_id = $post_or_comment->comment_ID;
$comment_post_id = $post_or_comment->comment_post_ID;
}
}
rewind_posts() will have no effect here. Just call wp_reset_query() right after the foreach loop ends.
Related
I am trying to fetch data from another custom post type books into the readers. I have written the code and the data shows up.
The challenge is that I want to check the echoed data $c[0] against the title of the current page.
Whenever I call the get_the_title() function I am instead getting the title of the other custom post type books. So there is no way I can add an if like so:
if (get_the_title()===$c[0]) {
//The echo code - see echo part of my code
}
When I echo the code, it goes into the top part of the page instead of inside the content area. I am suspecting this is the reason why I can't get the page title. I have tried researching on hooking to the content area and tried but I instead get a bunch of errors.
<?php
$posts = get_posts(array(
'numberposts' => 10,
'post_type' => 'fixtures-results'
));
if($posts)
{
foreach($posts as $post)
{
setup_postdata( $post );
$matches = str_replace("|% ","|%",get_field('fixtures_results'));
preg_match_all("#[A-z0-9 ./'áàâäãåǻăāąấấặắǎȧạàãáćĉċčççďđḑḋḍdéèêëĕěēęėềẽȩẹéĝ
ğġģǧǵḡĥħȟḣḥḩíìîïĭїĩīįǐĪỊ̣iỊǏĨị̣ịıíĵķǩḱḳļľŀĺĺóòôöõðőŏōỏǒǫȯoøồớòóõöñńņňʼnŋǹṅṇ
ŕŗřṙṛśŝşšṡṣşșţťŧțṫṭtúùûüůūűųũŭǔǘǚǜụuưüúŵŷýÿўỹẏỳỵyẙȳẙźżžẑẓḅḟḿṁṃṕṗṽṿḷẁẃẅẉẘ
ẘẋẍÒÓÔÕÖŐǑǪŌȮØÙÚÛǓǗǙǛŨŮŰŲÜỤŪĆĈČÇÀÁÂÃÄÅẠĄĀȦǍÈÉÊËĖĘĚẸẼĒȨḾṀṂŚŜŞŠṠṢŹŻŽẐẒŃŅŇ
ṄṆÑǸḢḤḨĤȞĹĻĽĿŢŤṪṬŖŘṘṚĜĠĢǦǴḠẀẂẄẈŴḊḌḐĎĐÐṔṖĶǨḰḲẊẌṼṾỴỸỲẎŸȲŶÝĴȷḄḞḶŁłÏÎÍÌıİ
ßıs-]+#[^#]+#", $matches, $countries);
$results = [];
foreach ($countries[0] as $c) {
$c = explode("#", $c);
$country_name = $c[0];
$results[$country_name] = [];
$params = explode("%", $c[1]);
foreach ($params as $key) {
if (!empty($key)) {
$test = explode("|", trim($key, '|'));
echo get_the_title($postID);
//echo $c[0] . $test[0] . $test[1] . $test[2].'<br>';
}
}
}
}
wp_reset_postdata();
}
?>
I have tried but can't get past that point. Thanks.
here i have a simple function but this show me data fom sql only in 1 div i want to show [ on div 1 show 1 data, in other div show 2 data, etc etc]...
function load_post($added_by)
{
global $Connection;
$SQL_3 = mysqli_query($Connection, "SELECT * FROM posts WHERE added_by='$added_by'");
$NumPosts = mysqli_num_rows($SQL_3);
$out['num_posts'] = $NumPosts;
while($Fetch_3 = mysqli_fetch_array($SQL_3))
{
$out['id'] = $Fetch_3['id'];
$out['text'] = $Fetch_3['text'];
$out['added_by'] = $Fetch_3['added_by'];
$out['mp4'] = $Fetch_3['mp4'];
$out['likes'] = $Fetch_3['likes'];
$out['youtube'] = $Fetch_3['youtube'];
$out['image'] = $Fetch_3['image'];
$out['date_added'] = $Fetch_3['date_added'];
return $out;
}
}
index.php.
$posts = load_post('gentritabazi');
<div class="settings_forms_content">
<?php echo $posts['text']; ?>
</div>
return finish immediately your function so only one iteration is done. You need to save your results in array and then after loop return that array, sth like this:
$out = array();
while($Fetch_3 = mysqli_fetch_array($SQL_3))
{
$out[] = $Fetch_3;
}
return $out;
and display:
$posts = load_post('gentritabazi');
foreach ($posts as $post) {
echo '<div class="settings_forms_content">';
echo $post['text'];
echo '</div>';
}
Lots to amend, so I commented the code rather than write an essay
function load_post($con, $added_by)
{
// dont use globals, use parameters
//global $Connection;
// select only what you want to see not `*`
$SQL_3 = mysqli_query($con, "SELECT id, text, added_by, mp4,
likes, youtube, image, data_added
FROM posts
WHERE added_by='$added_by'");
// not needed
//$NumPosts = mysqli_num_rows($SQL_3);
//$out['num_posts'] = $NumPosts;
while($Fetch_3 = mysqli_fetch_array($SQL_3))
{
/*
* THsi code would overwrite the last iteration of the while loop
$out['id'] = $Fetch_3['id'];
$out['text'] = $Fetch_3['text'];
$out['added_by'] = $Fetch_3['added_by'];
$out['mp4'] = $Fetch_3['mp4'];
$out['likes'] = $Fetch_3['likes'];
$out['youtube'] = $Fetch_3['youtube'];
$out['image'] = $Fetch_3['image'];
$out['date_added'] = $Fetch_3['date_added'];
*/
// now as you SELECT only what you want yo can simply do
$out[] = $Fetch_3;
//return $out; instantly terminates the function
}
return $out; // return the array
}
Now call your function
// pass the connection as a parameter
$posts = load_post($Connection, 'gentritabazi');
// if you want to know how many results were returned
$result_count = count($posts);
// process the returned array
foreach ( $posts as $post ) {
echo '<div class="settings_forms_content">';
echo $post['text'];
echo '</div>';
}
Your script is at risk of SQL Injection Attack
Have a look at what happened to Little Bobby Tables Even
if you are escaping inputs, its not safe!
Use prepared statement and parameterized statements
$posts = load_post('gentritabazi');
foreach ($posts ['text'] as $postText){
echo "<div class='settings_forms_content'>$postText</div>";
}
first line calls your function which returns the array $posts
this array looks like:
$posts = array(
"id" => array of ids
"text" => array of texts
...
);
if you want to access the third text it would be like this:
$posts ['text'][3]
the foreach iterates to your $post array with index "text" -> which is also an array
every value in this array, $post['text'] will be referenced with $postText -> that means:
$post['text'][1] = $postText (first time looping through foreach-loop)
$post['text'][2] = $postText (secondtime looping through foreach-loop)
..
if you are familiar with loops, a foreach is just the short version for
for(var $i=0;$i<length($posts['text'];$i++){
echo "<div class='settings_forms_content'>$posts['text'][i]</div>";
}
OK, I have a very specific question that I hope someone can shed some light on.
I have a page that lists authors outputting using the following code
<?php
$display_admins = false;
$order_by = 'post_count'; // 'nicename', 'email', 'url', 'registered', 'display_name', or 'post_count'
$role = ''; // 'subscriber', 'contributor', 'editor', 'author' - leave blank for 'all'
$hide_empty = true; // hides authors with zero posts
if(!empty($display_admins)) {
$blogusers = get_users('orderby='.$order_by.'&role='.$role);
} else {
$admins = get_users('role=administrator');
$exclude = array();
foreach($admins as $ad) {
$exclude[] = $ad->ID;
}
$exclude = implode(',', $exclude);
$blogusers = get_users('exclude='.$exclude.'&orderby='.$order_by.'&role='.$role.'&order='.'DESC');
}
$authors = array();
foreach ($blogusers as $bloguser) {
$user = get_userdata($bloguser->ID);
if(!empty($hide_empty)) {
$numposts = count_user_posts($user->ID);
if($numposts < 1) continue;
}
$authors[] = (array) $user;
}
echo '<ul class="contributors">';
foreach($authors as $author) {
$display_name = $author['data']->display_name;
$avatar = get_wp_user_avatar($author['ID'], 'medium');
$author_profile_url = get_author_posts_url($author['ID']);
$filter = get_userdata($author['ID'])->yim;
echo '<li><div class="home ', $filter,' "><div class="feature-image">', $avatar , '</div>
<div class="post-title"><h3>', $display_name, '</h3></div>
</div>
</li>';
}
echo '</ul>';
?>
(I got this from another support topic and tweaked it, although I can't remember where)
At the moment, the $filter variable is just a string I enter in the 'Yahoo IM' profile box (a dirty fix to test the filter). I'd like this to actually be a list of the categories (as slugs that I will output in to the class="" part of the loop) that the author has posted in.
I essentially want to be able to filter the authors by category that they have posted in, and the filter I'm using (Isotope) operates using the class, so outputting the categories in to the class of the markup is what I'm after.
Any suggestions gratefully received!
// Returns the posts made by the author
$authorPosts = get_posts("author={$author['ID']}");
$categoryList = array(); // reset previous values
foreach ($authorPosts as $post) {
$postCategories = get_the_category($post->ID);
// Add to the categories the author has posted in
foreach ($postCategories as $category)
$categoryList[] = $category->slug;
}
// Removes duplicate categories
$categoryList = array_unique($categoryList);
You can then use $filter = implode(' ', $categoryList); and add it to your html.
RE not storing the array from the other answer, you can just echo out the slugs there and then like this:
$authorPosts = get_posts("author={$author['ID']}");
foreach ($authorPosts as $post) {
$postCategories = get_the_category($post->ID);
// Add to the categories the author has posted in
foreach ($postCategories as $category)
echo($category->slug);
}
otherwise if you want to put your PHP at the top and echo out the slugs further down the page pop there where ever you want to echo them:
$i = 0;
foreach($categoryList as $category) {
echo($categoryList[$i]);
$i++;
}
I am using the cms perch to retrieve data using various functions. I am retrieving product items from various sub pages. The code I have so far is working as it should and can be seen here: http://www.ww.thirdfloordesign.net/products/70mm-couplers/
$raw = perch_pages_navigation(array(
'from-path'=>'*',
'skip-template'=>true
));
if (count($raw)) {
$items = $raw;
} else {
// add else statement to output warning 'no products found in this category' or something
}
foreach($items as $item) {
$product['ID'] = $item['pageNavText'];
$product['title'] = $item['pageTitle'];
$product['path'] = $item['pagePath'];
$product['parent'] = $item['pageSubpagePath'];
PerchSystem::set_vars(array(
'product-id'=>$product['ID'],
'product-title'=>$product['title'],
'product-path'=>$product['path'],
'product-parent'=>$product['parent']
));
$product['image'] = perch_content_custom('Image', array(
'page'=>$product['path'],
'template'=>'product/_image.html',
'sort'=>'_order',
'count'=>1
), true);
PerchSystem::set_var('product-image', $product['image']);
$items[] = perch_content_custom('Product', array(
'page'=>$product['path'],
'template'=>'product/_product.html'
), true);
}
Where the data needs to be outputted I am using the following code and it seems to be working as it should except it is also echoing an array which can be seen on the page. Is it because I am using duplicate $variables / array names? Solutions please
<?php
if (!empty($items)) {
?>
<ul class="product-grid">
<?php
foreach($items as $item) {
echo $item;
}
?>
</ul>
<?php
} else {
?>
<p class="alert alert-warning"><i class="icon-warning-sign"></i>No products found!</p>
<?php } ?>
I have the code below. $related is array result of db query and contains data.
Queried data consist of posts belonging to different groups (post_type). I want to group the queried objects within their post_type. The code below works BUT... what I want is create different ULs for each post_type. As it is below, there will be a UL element foreach post found in the query. So UL should stay out of foreach, but on the other hand how can i get post_type out of foreach? I am a bit lost here :(
$related = p2p_type( 'accommmodation-to-places' )->get_connected( get_queried_object_id() );
foreach($related->posts as $post) {
echo '<ul class="related-'.$post->post_type.'">'; // this shouldn't be here
if($post->post_type == 'hotels') {
echo '<li>'.get_the_post_thumbnail($post->id, '48').$post->post_title.'</li>';
}
echo '</ul>'; // this shouldn't be here
}
wp_reset_query();
So first, group the posts by their type:
$groups = array();
foreach ($related->posts as $post) {
$groups[$post->post_type][] = $post;
}
Then loop through the groups and output the lists:
foreach ($groups as $type => $posts) {
printf('<ul class="%s">', htmlspecialchars($type));
foreach ($posts as $post) {
printf('<li>...</li>', ...);
}
echo '</ul>';
}