I'm trying to figure out how to get the current post ID from my main wp_query loop to work in the nested loop..
I've added my loops below with most HTML removed to make it cleaner to see.
I need to replace the "16" where it says "$currentID = 16;" in the nested loop with the actual current post ID from the main loop.
<?php $related_query = new WP_Query( 'post_type=post&posts_per_page=-1' ); ?>
<?php if( $related_query->have_posts() ): ?>
<?php while ( $related_query->have_posts() ) : $related_query->the_post(); ?>
<?php the_ID(); ?>
<?php the_time('F j, Y'); ?>
<?php the_category(); ?>
<?php echo get_edit_post_link(); ?>
<?php echo get_post_meta(get_the_ID(), 'cf_meta-desc', true); ?>
<?php echo get_post_meta(get_the_ID(), 'cf_xray', true); ?>
<?php the_tags(); ?>
<ul>
<h4>Recommended Articles</h4>
<?php
$related_cfs = get_post_meta( get_the_ID(), 'cf_related' );
foreach($related_cfs as $related_cf) {
echo '<li>';
echo '<span class="related-links__id">' .$related_cf. '</span>';
echo '<span class="related-links__title"><a target="_blank" href="' .get_permalink($related_cf). '">' .get_the_title($related_cf). '</a></span>';
echo '<span class="related-links__edit"><a target="_blank" href="' .get_edit_post_link($related_cf). '">edit</a></span>';
echo '</li>';
} ?>
</ul>
<?php global $post;$backup=$post; //saves main query data before calling nested query ?>
<!-- BEGIN NESTED LOOP -->
<?php $referral_query = new WP_Query( 'meta_key=cf_related&posts_per_page=-1' ); ?>
<ol>
<h4 class="referring-links__header">Linkbacks (<?php
$meta_key = 'cf_related';
$currentID = 16;
$sql = "SELECT count(DISTINCT pm.post_id)
FROM $wpdb->postmeta pm
JOIN $wpdb->posts p ON (p.ID = pm.post_id)
WHERE pm.meta_key = '$meta_key'
AND pm.meta_value = '$currentID'
";
$count = $wpdb->get_var($sql);
echo "$count";
?>)
</h4>
<?php while ( $referral_query->have_posts() ) : $referral_query->the_post(); ?>
<?php
$currentID = 16;
$arrayCFrelated = get_post_custom_values('cf_related');
if (in_array($currentID, $arrayCFrelated))
{ ?>
<li>
<?php the_ID(); ?>
<?php the_title(); ?>
<?php echo get_edit_post_link(); ?>
</li>
<?php } ?>
<?php endwhile; ?>
</ol>
<!-- END NESTED LOOP -->
<?php $post=$backup; //brings back main query data before called nested query ?>
<?php echo get_post_meta(get_the_ID(), 'cf_img-feature', true); ?>
<?php endwhile; ?>
<?php else: ?>
<p class="center">Nothing found.</p>
<?php endif; ?>
<?php wp_reset_query(); ?>
The code you posted is very hard to read because it is all nested and distributed between opening and closing php tags.
First of all - You should consider to get familiar with functions and objects as an alternative to nest everything within the same loop. This will also help other developers who work with you to understand your code.
As for your problem. Try using other types of loops to get indices within the loop. For example:
for ($i1=0; $i1 < count($yourarray); $i1++) {
// ...
echo "index: $i1 <br />";
echo "value: {$yourarray[$i1]}";
}
or
foreach ($array AS $idx => $value) {
// ...
echo "index: $idx <br />";
echo "value: $value";
}
I know this question is old but I run into the same issue recently.
If you have a main loop and want to get the ID (or any other data) of the current post to be used inside of a nested wp_query then use the global $post object.
Using 'get_the_id()' inside of the nested wp_query will return the id of the current post in the nested wp_query and not the main query
Example:
$post_id = $post->ID;
Related
I'm working on WordPress custom fields and I need to write PHP if-else conditions in a loop whether it is the first child or last child of the ul list. but I don't know how to apply, kindly please help me to solve it
Here is my code below
<?php if( have_rows('chart') ): ?>
<ul class="list-unstyled">
<?php while( have_rows('chart') ): the_row();
$sr_no = get_sub_field('sr_no');
$list_content = get_sub_field('list_content');
?>
<li><div><span class="w-num"><?php echo $sr_no; ?></span><?php echo $list_content; ?></div><span class="chart-divider"><span class="chart-divider-r"></span></span></li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
Count the entries for rows.
Set up a counter, and every time you iterate increase.
<?php if( have_rows('chart') ): ?>
<ul class="list-unstyled">
<?php
$counter = 1;
$total-row = // Figure out how to count(rows), or something like that
while( have_rows('chart') ): the_row();
$sr_no = get_sub_field('sr_no');
$list_content = get_sub_field('list_content');
if($counter == 1){
// First Row
} elseif ($counter == $total-row){
// Last Row
}
?>
<li><div><span class="w-num"><?php echo $sr_no; ?></span><?php echo $list_content; ?></div><span class="chart-divider"><span class="chart-divider-r"></span></span></li>
<?php
$counter++;
endwhile; ?>
</ul>
<?php endif; ?>
Please try with below:
The result you will see in the li as a class
If fist li, you will see the first_class
If last li, you will see the last_class
Else only some_class
<?php
$Total_charts_count = wp_count_posts( 'chart' )->publish; //Total count of charts
$chart_number = 1; //Loop starting point.
if( have_rows('chart') ): ?>
<ul class="list-unstyled">
<?php
while( have_rows('chart') ): the_row();
$sr_no = get_sub_field('sr_no');
$list_content = get_sub_field('list_content');
// First item
if($chart_number == 1) {
$class = 'some_class first_class';
// Last item
} else if ($chart_number == $Total_charts_count) {
$class = 'some_class last_class';
// Not first / Not last item
} else {
$class = 'some_class';
}
?>
<li class="<?php echo $class; ?>">
<div>
<span class="w-num"><?php echo $sr_no; ?></span>
<?php echo $list_content; ?>
</div>
<span class="chart-divider">
<span class="chart-divider-r"></span>
</span>
</li>
<?php
$chart_number++;
endwhile; ?>
</ul>
<?php endif;
?>
Hope it's work for you.
I want to get some data from a MySql database which has the same ID but different values. see the image (this is just a sample)
Although the venue styles are different, I want to pull all the styles with the same ID. I'm using a foreach loop to get the data from the database.
How can I improve my code to achieve what I want.
<?php
$myrows = $wpdb->get_results( "SELECT vf_venues.title, vf_venues.mainimage,
vf_venues.permalink, vf_venuestyles.slug
FROM vf_venues
LEFT JOIN vf_venuestyles ON vf_venuestyles.vid=vf_venues.vid WHERE
vf_venuestyles.vid=vf_venues.vid" );?>
<div class="venue-list venue-grid">
<?php
foreach ( $myrows as $myrow ) {
//pull the data from the DB
"<pre>"
$venueName = $myrow->title;
$mainImage = $myrow->mainimage;
$permalink = $myrow->permalink;
$slug = $myrow->slug;
$vid = $myrow->vid;
"<pre>"
?>
<li class="venue-block block">
<div class="venue-img">
<a href="<?php echo $permalink; ?>">
<img src="<?php echo $mainImage; ?>">
</a>
</div>
<div class="venue-details"><h2><?php echo $venueName; ?></h2></div>
<?php echo $slug; ?>
<?php echo $vid; ?>
</li>
<?php
}
?>
</div>
I managed to fix this by creating a for loop within the existing for loop. I then created a sql query to pull the venue styles for that venue.
I am trying to get my code to return the last 3 posts from wordpress in Magento using the Fishpig extension. This is the code I have so far, but it appears to returning posts more than once. I also need it to just return posts, as it also returns pages at the moment.
<?php $resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_read');
$query = "SELECT p.id,p.post_title,p.post_name ,p.post_content,p.comment_count,pm.meta_value FROM wp_postmeta AS pm INNER JOIN wp_posts AS p ON pm.post_id=p.ID ORDER BY p.post_date";
$results = $readConnection->fetchAll($query);
?>
<?php
foreach($results as $row) { ?>
<?php if($row['post_title']!='Auto Draft'):
//Get url from pm.meta_value
/********/
$readConnection1 = $resource->getConnection('core_read');
$query1 ="SELECT * FROM `wp_postmeta` WHERE `post_id` = '".$row['meta_value']."' AND meta_key='_wp_attached_file'";
$results1 = $readConnection->fetchAll($query1);
$url='/news/wp-content/uploads/'.($results1[0]['meta_value']);
?>
<div class="blog-post-image">
<img src="<?php echo $url; ?>">
</div>
<div class="blog-post-content">
<?php ?>
<h3> <?php echo $row['post_title'];?></h3>
<p class="blog-content"> <?php $content = $row['post_content']; echo $string = substr($content,0,220); if(strlen($content)>220){echo "...";} ?></a></p>
More Info
</div>
<?php endif; ?>
<?php
if($counter == 4)
{
break;
}
$counter++;
}
?>
To display 3 posts and display the post title, URL, image and post content (or excerpt), you would need the following code:
<?php $posts = Mage::getResourceModel('wordpress/post_collection')
->addIsViewableFilter()
->addPostTypeFilter('post')
->setPageSize(3)
->load() ?>
<?php if (count($posts) > 0): ?>
<ul>
<?php foreach($posts as $post): ?>
<li>
<h2>
<?php echo $this->escapeHtml($post->getPostTitle()) ?>
</h2>
<?php if ($image = $post->getFeaturedImage()): ?>
<img src="<?php echo $image->getAvailableImage() ?>" alt="" />
<?php endif; ?>
<?php echo $post->getPostContent() ?>
<?php
/**
* You could also use:
* echo $post->getPostExcerpt(20)
* This would display the first 20 words of the post content
* or the manually entered excerpt
**/
?>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
This has been writte quickly by hand and hasn't been tested but should work fine.
I have this code, and I need to close a row every 4 post. Every post is inside a div. I tried some things but I coudn't implement to my code.
<?php
echo "<div class='row'>";
global $post;
$all_events = tribe_get_events(
array(
'eventDisplay'=>'upcoming',
//'posts_per_page'=>10,
)
);
foreach($all_events as $post) {
setup_postdata($post);
?>
<div class="col-sm-3">
<span class="event-date"><?php echo tribe_get_start_date($post->ID, true, 'j M'); ?></span>
<h3><?php the_title(); ?></h3>
<?php if ( has_post_thumbnail() ) { ?>
<div class="event-thumb">
<?php the_post_thumbnail('thumbnail'); ?>
</div>
<div class="event-excerpt">
<?php the_excerpt(); ?>
</div>
<?php } else { ?>
<div class="event-content">
<?php the_content(); ?>
</div>
<?php } ?>
</div>
<?php } //endforeach ?>
<?php wp_reset_query(); ?>
<?php
echo "<div class='row'>";
global $post;
$all_events = tribe_get_events(
array(
'eventDisplay'=>'upcoming',
//'posts_per_page'=>10,
)
);
$count = 1;
foreach($all_events as $post) {
setup_postdata($post);
?>
<div class="col-sm-3">
<span class="event-date"><?php echo tribe_get_start_date($post->ID, true, 'j M'); ?></span>
<h3><?php the_title(); ?></h3>
<?php if ( has_post_thumbnail() ) { ?>
<div class="event-thumb">
<?php the_post_thumbnail('thumbnail'); ?>
</div>
<div class="event-excerpt">
<?php the_excerpt(); ?>
</div>
<?php } else { ?>
<div class="event-content">
<?php the_content(); ?>
</div>
<?php } ?>
</div>
<?php
if($count == 4){
echo "<div class='seperator'></div>";
$count =1;
}
?>
<?php $count++; } //endforeach ?>
<?php wp_reset_query(); ?>
I'd actually solve this 100% in CSS, so you don't need any counting or handling inside your PHP code.
Have a look at this JSFiddle.
float: left will cause the single elements to all follow each other (left aligned).
clear: left on every 4 * n + 1-th element (nth-child(4n+1)) will clear this, essentially forcing a line break.
There is one caveat to this: If there's no room for all 4 entries in one row, you'll end up with additional wrapping, which can be avoided by defining a fixed width for the container.
A simplified in-code version for PHP would just count the fields written and add a line break as necessary:
$i = 1; // counter
foreach ($events as $event) { // iterate over all events
if ($i++ % 4 == 0) // a % b will be 0 for 4, 8, etc.
echo '<br />'; // print the line break using whatever HTML you see fit.
print_event($event); // print the actual event
}
You might ask whether I check for the line break before actually printing an event: That's to prevent additional line breaks if the number of entries is a multiple of 4, i.e. I avoid having an empty trailing line.
You need the modulo operator. It works like this:
$i == 0;
foreach($some_array as $some_value){
if ($i % $number_to_divide_by == 0) {
// do something here every nth time
}
$i++;
}
I have the following PHP array structure:
$set = array();
$set[] = array('firstname'=>'firstname 1',
'lastname'=>'lastname 1',
"bio"=>array('paragraph 1 of the bio, 'paragraph 2 of the bio','paragraph 3 of the bio'),
);
I then access the array with the following:
<?php $counter = 0;
while ($counter < 1) : //1 for now
$item = $set[$counter]?>
<h1><?php echo $item['firstname'] ?></h1>
<h1><?php echo $item['lastname'] ?></h1>
<?php endwhile; ?>
I'm uncertain how I can loop through the "bio" part of the array and echo each paragraph.
So as a final output, I should have two h1s (first and last name) and three paragraphs (the bio).
How can I go about doing this?
Use foreach loop
foreach($item['bio'] as $listitem) {
echo $listitem;
}
You don't need to use a manual counter, you can use foreach. It's generally the easiest way and prevents off-by-one errors.
Then you need a second inner loop to loop through the bio.
<?php foreach ($set as $item): ?>
<h1><?php echo $item['firstname'] ?></h1>
<h1><?php echo $item['lastname'] ?></h1>
<?php foreach ($item['bio'] as $bio): ?>
<p><?php echo $bio; ?></p>
<?php endforeach; ?>
<?php endforeach; ?>
On a related note; you probably want to look into escaping your output.
Add into the while loop also this:
<?php foreach ($item['bio'] as $paragraph): ?>
<p><?php echo $paragraph; ?></p>
<?php endforeach; ?>
Note that used coding style is not optimal.
Try:
foreach($set as $listitem) {
if(is_array($listitem)) {
foreach($listitem as $v) //as $set['bio'] is an array
echo '<h1>' .$v . '</h1>';
} else
echo '<p>'.$listitem.'</p>';
}