I'm fetching an RSS feed with Simplepie on a Wordpress blog. Each RSS item has a div container, and I want each one to have a unique id number (something like <div id="div-#">).
How would I generate a unique number for each item? Here's the code I'm using:
<ul>
<?php include_once(ABSPATH . WPINC . '/feed.php');
$rss = fetch_feed(http://www.example.com);
if (!is_wp_error( $rss ) ) :
$maxitems = $rss->get_item_quantity(6);
$rss_items = $rss->get_items(0, $maxitems);
endif; ?>
<?php
if ($maxitems == 0) echo '<li>No items.</li>';
foreach ( $rss_items as $item ) : ?>
<a href="<?php echo $item->get_link();?>">
<?php
echo '<li><div class="item-headline" id="div-">'.
$item->get_title().
'</div><div class="item-info">'.
$item->get_description().
'</div></li>';
?>
</a>
<?php endforeach; ?>
</ul>
Use get_id(true) to get a unique MD5 hash of the item.
echo '<li><div class="item-headline" id="div-'.$item->get_id(true).'">'.
Try something like:
<?php
foreach ($feed->get_items() as $item) {
echo '<div id="item-<?php echo $num ?>">';
// ...
}
Related
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;
I'm making a filterable portfolio using jquery. I have different categories and I'm getting all the posts within one category and then sorting them by their tags. This works fine with one word tags, but it does not work when the tag is more than one word. How can it work with more than one word tag?
My code:
<div class="tagwrapper">
<div class="posttags">
<?php
query_posts('category_name=Sport');
if (have_posts()) : while (have_posts()) : the_post();
$posttags = get_the_tags();
// print_r($posttags);
// echo gettype($posttags);
if ($posttags) {
foreach($posttags as $tag) {
// echo gettype($tag);
//echo $tag->name;
$all_tags_arr[] = $tag -> name; //USING JUST $tag MAKING $all_tags_arr A MULTI-DIMENSIONAL ARRAY, WHICH DOES WORK WITH array_unique
}
}
endwhile; endif;
$unique_tags_arr = array_unique($all_tags_arr); //REMOVES DUPLICATES
if ($unique_tags_arr) {
echo '<ul class="jquery">';
echo '<li data-filter=".filterable">';
echo "Alle";
echo '</li>';
foreach ($unique_tags_arr as &$value) {
echo '<li data-filter=".'.$value .'"> '.$value.'</li>';
}
echo '</ul>';
}
?>
</div>
<div id="news">
<?php
while (have_posts()) : the_post();
//generate the article list for all articles within the sports category
//the $tags_class variable is a whitespace delimited string of tags for this post
//print_r($value);
$posttags = get_the_tags();
echo '<article class="filterable ';
if ($posttags) {
foreach($posttags as $tag) {
echo $tag->name . ' ';
}
}
echo '">';
?>
<h3> <?php the_title(); ?></h3>
<?php the_post_thumbnail(); ?>
<?php echo '</article>'; ?>
<?php endwhile; ?>
</div>
</div>
The reason is because $value can be a string with whitespace such as my cool category. And the filterable ruleset isn't built to handle whitespace as 1 value. What you actually want is to check for whitespace in the string and then replace it with -.
if(preg_match('/\s/', $value) $value = str_replace(" ", "-", $value);
Then you will get:
my-cool-category
You will also need to make this modification in the following code:
foreach($posttags as $tag) {
if(preg_match('/\s/', $tag) $tag = str_replace(" ", "-", $tag);
}
Right now I have the following PHP:
<?php
$pages = get_pages( array( 'sort_column'=>'menu_order', 'parent'=>'0') );
foreach ($pages as $page_data) {
$content = apply_filters('the_content', $page_data->post_content);
$title = $page_data->post_title;
$slug = $page_data->post_name;
$pageid=$page_data->ID;
echo '<div class="section'.(($title=='intro')?' intro-section':"").'">';
echo $content;
echo "</div>";
}
?>
There are 5 Pages, 2 of which have many child Pages. I want to take the above code further one level, so that each page will have its own wrapper, and, if a Page has children Pages, those pages will be placed within the same .section, but each within a separate div. Any advice? I'm a bit inexperienced in Wordpress so any help would be great. Below should give an example of what I want:
<div class="section">
<div class="page parent"></div>
</div>
<div class="section">
<div class="page parent"></div>
<div class="page child"></div>
<div class="page child"></div>
</div>
<div class="section">
<div class="page parent"></div>
</div>
Below is the code I'm working with right now.
<?php while (have_posts()) : the_post(); ?>
<?php
$pages = get_pages( array( 'sort_column'=>'menu_order', 'parent'=>'0') );
foreach ($pages as $page_data) {
$content = apply_filters('the_content', $page_data->post_content);
$title = $page_data->post_title;
$slug = $page_data->post_name;
$pageid=$page_data->ID;
//Put a container around every page's content
if (count(get_pages('child_of=' . $page_data->ID.''))) {
// Loop through $page_data array to print the div you want
echo '<div class="section">';
echo '<div class="slide">';
echo $content;
echo "</div>";
$children = get_pages('child_of=' . $page_data->ID.'');
foreach( $children as $child ) {
$childcontent = apply_filters('the_content', $child->post_content);
echo '<div class="slide">';
echo $childcontent;
echo "</div>";
}
echo "</div><!--end section-->";
} else {
echo '<div class="section'.(($title=='intro')?' intro-section':"").'">';
echo $content;
echo "</div>";
}
}
?>
<?php endwhile ?>
Use child_of parameter of get_pages() function inside the loop. This parameter lists the sub-pages of a single Page only. It uses the ID for a Page as the value.
Eg.
if (count(get_pages('child_of=' . $page_data->ID))) {
// Loop through $page_data array to print the div you want
}
I am trying to give an alternate class to each LI foreach.
i.e.
<li class="odd">
text
</li>
<li class="even">
text
</li>
<li class="odd">
text
</li>
<li class="even">
text
</li>
This is my code:
<ul>
<?php foreach ($this->item->extra_fields as $key=>$extraField): ?>
<?php if($extraField->value): ?>
<li class="<?php echo ($key%2) ? "odd" : "even"; ?> type<?php echo ucfirst($extraField->type); ?> group<?php echo $extraField->group; ?>">
Text here
</li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
Please can anyone help...
Thanks
try :
<?php $count = 0; // need to set first value
<?php foreach ($this->item->extra_fields as $key=>$extraField): ?>
<?php if($extraField->value): ?>
<li class="<?php echo (++$count % 2) ? "odd" : "even"; ?> type <?php echo ucfirst($extraField->type); ?> group<?php echo $extraField->group; ?>">
Text here
</li>
<?php endif; ?>
<?php endforeach; ?>
Link to pre/post increment docs if needed
I would do it that way .. it's key independent and you better see what the li-class will look like.
<ul>
<?php
foreach ($this->item->extra_fields as $key=>$extraField) {
if($extraField->value) {
$toggle = ($toggle=="odd"?"even":"odd");
echo '<li class="',$toggle,' type',ucfirst($extraField->type),' group', $extraField->group,'">';
echo 'Text here';
echo '</li>';
}
}
?>
</ul>
jQuery can easily do this if that's an option for you. It's :odd and :even selectors should do just what you're looking for without too much hassle.
I know this is old, but I humbly present a cleaner solution:
<ul>
<?php
$odd = true;
foreach ( $this->item->extra_fields as $key => $extraField ) {
// Output template.
$template = '<li class="%1$s">%2$s</li>';
// Create our classes.
$classes = [
( $odd ) ? 'odd' : 'even',
'type' . ucfirst($extraField->type),
'group' . $extraField->group
];
// Create our class string.
$class_string = implode( ' ', $classes );
// Print our content out.
printf( $template, $class_string, 'Text here' );
// Flip the classname for next time.
$odd = ! $odd;
}
?>
</ul>
It could of course be cleaner still, by using fewer variables. This is just my style.
I am a beginner to php and am stuck on trying to call out sub-categories of just one parent category as links
I got to this and it’s bringing up the getName but the getUrl() isn’t returning any URL at all....
<?php
$children = Mage::getModel('catalog/category')->getCategories(3);
foreach ($children as $category):
echo '<li>' . $category->getName() . '</li>';
endforeach;
?>
The output code is just <li>name of sub-cat</li>
Anybody have any ideas? Please?
Thanks,
Kayla
Please try this code I think you did this code but this is very helpful for someone who is searching this code
<?php
$children = Mage::getModel('catalog/category')->getCategories(3);
foreach ($children as $category):
$category = Mage::getModel('catalog/category')->load($category->getId());
echo '<li>' . $category->getName() . '</li>';
endforeach;
?>
I don't know why #Dhanapal solution has not worked for me, so I used:
$categories = Mage::getModel('catalog/category')->load('3')->getChildrenCategories();
foreach ($children as $category):
$category = Mage::getModel('catalog/category')->load($category->getId());
echo '<li>' . $category->getName() . '</li>';
endforeach;
For some reason, the above answer did not work for me. I am also using Magento 1.7.x.
I found Magento displays subcategories description on category list.phtml link to be helpful.
I am trying to do the same as you so I adjusted the above answer from
<?php $children = explode( ",", $this->getCurrentCategory()->getChildren() ); ?>
<div class="category-products">
<ul class="products-grid">
<?php foreach( $children as $child ): ?>
<?php $_child = Mage::getModel( 'catalog/category' )->load( $child ); ?>
<li class="item"><?php echo $_child->getDescription(); ?></li>
<?php endforeach; ?>
</ul>
</div>
to:
<?php $children = explode( ",", $this->getCurrentCategory()->getChildren() ); ?>
<div class="category-products">
<ul class="products-list">
<?php foreach( $children as $child ): ?>
<?php $_child = Mage::getModel( 'catalog/category' )->load( $child ); ?>
<li class="item"> <?php echo $_child->getName() ?> </li>
<?php endforeach; ?>
</ul>
</div>
Just like the above answer, you can change the div class to
<div class="products-grid">
instead of listing them. But you have asked how to list.
I hope this helps people in the future. There are tons of other related questions on Stack overflow as well.
Well, This was a pain in the ass. I've made a function for it that lists all the subcategories and sub-sub-categories of the category that you want to display.
<?PHP
//get the children of the current category
function getChildrenInterStore($id) {
$returnstring = '';
$subCats = Mage::getModel('catalog/category')->load($id)->getChildren();
//get sub category ids
$subCatIds = explode(',',$subCats);
if (count($subCatIds) > 0):
foreach($subCatIds as $subCatId):
$subCat = Mage::getModel('catalog/category')->load($subCatId);
if($subCat->getIsActive()):
$returnstring .= '
<li class="other-toggle sm_megamenu_lv1 sm_megamenu_drop parent">
<a class="sm_megamenu_head sm_megamenu_drop" href="'.$subCat->getUrl().'">
<span class="sm_megamenu_icon">
<span class="sm_megamenu_title">'.$subCat->getName().'</span>
</span>
</a>
</li>';
$returnstring .= getChildrenInterStore($subCatId);
endif;
endforeach;
endif;
return $returnstring;
}
?>
<div class="mega-left-title">
<strong>Categorieen</strong>
</div>
<div class="css_effect sm_megamenu_wrapper_vertical_menu sambar">
<div class="sambar-inner">
<ul class="sm-megamenu-hover sm_megamenu_menu sm_megamenu_menu_black">
<?PHP echo getChildrenInterStore('17'); ?>
</ul>
</div>
</div>