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.
Related
Im trying to get two of the latest posts from Wordpress that include featured images. Need to get the post title, content (character limited) and the featured image. I have this so far, all that is missing is the featured image.
<div class="block block-blog block-recent-posts">
<?php $resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_read');
$query = "SELECT `id`, `post_title`,`post_name` ,`post_content`, `comment_count` FROM `wp_posts` WHERE `post_type`='post' ORDER BY `comment_count` DESC LIMIT 10";
$results = $readConnection->fetchAll($query);
?>
<ul>
<?php
$counter = 0;
foreach($results as $row) { ?>
<?php if($row['post_title']!='Auto Draft'): ?>
<li class="item">
<?php echo $row['post_title'];?>
<p class="blog-content"> <?php $content = $row['post_content']; echo $string = substr($content,0,220); if(strlen($content)>220){echo "...";} ?></a></p>
</li>
<?php endif; ?>
<?php
if($counter == 2)
{
break;
}
$counter++;
}
?>
</ul>
Try this:
I have updated your query and added another query to get post image url :
<div class="block block-blog block-recent-posts">
<?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 WHERE pm.meta_key = '_thumbnail_id' AND p.post_type='post' ORDER BY p.post_date DESC LIMIT 10";
$results = $readConnection->fetchAll($query);
?>
<ul>
<?php
$counter = 0;
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='www.yoursite.com/wp-content/uploads/'.($results1[0]['meta_value']);
echo $url; //YOUR URL just set your site name
//So final url YOUR--> SITENAME/wp-content/uploads/pathfromquery
?>
<li class="item">
<?php echo $row['post_title'];?>
<p class="blog-content"> <?php $content = $row['post_content']; echo $string = substr($content,0,220); if(strlen($content)>220){echo "...";} ?></a></p>
</li>
<?php endif; ?>
<?php
if($counter == 2)
{
break;
}
$counter++;
}
?>
</ul>
You shouldn't really be using raw SQL here. As a work around, couldn't you do either of the following:
1) Select more than 2 posts (eg. 5) and loop through them and display the 2 that have featured images
2) Ensure all posts have featured images and then select the first 2 posts
3) Use a collection of posts and then add your custom SQL to that.
This code will get 2 posts and add the _thumbnail_id to the collection. You can add some code to this to check this field exists (use $posts->load(true) to debug the SQL query and $posts->getSelect()->where() to add the custom filter)
<?php $posts = Mage::getResourceModel('wordpress/post_collection') ?>
<?php $posts->addPostTypeFilter('post') ?>
<?php $posts->addIsViewableFilter() ?>
<?php // Limit the collection to 2 posts. Change this number or remove this line completely to include all posts
<?php $posts->setPageSize(2) ?>
<?php // Adds the _thumbnail_id meta field to the collection ?>
<?php // This can be used for checking in the SQL whether a post has a featured image ?>
<?php $posts->addMetaFieldToSelect('_thumbnail_id') ?>
<?php $posts->load() ?>
<?php if (count($posts) > 0): ?>
<ul>
<?php foreach($posts as $post): ?>
<li>
<h2><?php echo $post->getPostTitle() ?></h2>
<?php if ($image = $post->getFeaturedImage()): ?>
<img src="<?php echo $image->getAvailableImage() ?>" alt="" />
<?php endif; ?>
<div class="post-content"><?php echo $post->getPostContent() ?></div>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
Can anyone supply me with some code that will grab the last 3 blog posts from Wordpress within Magento using the Fishpig extension. Can't find a template to use anywhere. Need to grab blog title, content and featured image.
I believe i'm on the wrong track with what I have so far.
<?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++;
}
?>
Thanks.
I am creating a forum and the code I am putting in this thread is the page that shows all of the forum categories. I have this setup where I have an id, category_section, category_title, and category_description. The way it is structured now is that it creates a new category section border every time I add a new category title in my database. This is what I mean by this:
As an example:
My category section is called Shoes, my category titles are Nike, Adidas, Reebok
Currently, it does:
Shoes
Nike
Shoes
Adidas
Shoes
Reebok
But it should do this:
Shoes
Nike
Adidas
Reebok
How can I get my current code to do this?
$query = mysqli_query($con,"SELECT * FROM forum_categories ORDER BY category_title DESC");
$numrows = mysqli_num_rows($query);
$categories = "";
if($numrows > 0){
while($forum_row = mysqli_fetch_assoc($query)){
$categoryid = $forum_row['id'];
$category_section = $forum_row['category_section'];
$categoryTitle = $forum_row['category_title'];
$categoryDescription = $forum_row['category_description'];
$categories = "<a href='forum_view_category.php?cid=".$categoryid."'>"
. $categoryTitle . "</a>";
//$categories .= "<a href='forum_view_category.php?cid=".$categoryid
//."' class='cat_links'>" . $categoryTitle . "</a>" " - " . $categoryDescription .;
?>
<div class="category_section">
<?php echo $category_section; ?>
</div>
<div class="category_border">
<div class="discussions_left">
<div class="discussions_category_title">
<?php echo $categories; ?>
</div>
<div class="discussions_category_description">
<?php echo $categoryDescription; ?>
</div>
</div>
<div class="discussions_right">
</div>
</div>
<?php
}
//echo $categories;
} else {
echo "<p>There are no posted categories available yet. </p>";
}
I would change your SQL to order by section first, then the title.
SELECT * FROM forum_categories ORDER BY category_section DESC, category_title DESC
After you've done that, define an if statement to check if the current section is the same as the previous statement.
If so, move one.
If not, echo the new section title.
I've cleaned up your code a bit and switched to the Alternative syntax for control structures for readability and maintainability.
PHPFiddle Demo (faked MySQL)
<?php
$query = mysqli_query($con,"SELECT * FROM forum_categories ORDER BY category_section DESC, category_title DESC");
$category_section = "";
?>
<?php if(mysqli_num_rows($query) > 0): ?>
<?php while($cat = mysqli_fetch_assoc($query)): ?>
<?php if($cat['category_section'] !== $category_section): ?>
<?php $category_section = $cat['category_section'] ?>
<div class="category_section">
<?= $category_section ?>
</div>
<?php endif; ?>
<div class="category_border">
<div class="discussions_left">
<div class="discussions_category_title">
<a href="forum_view_category.php?cid=<?= $cat['id'] ?>">
<?= $cat['category_title'] ?>
</a>
</div>
<div class="discussions_category_description">
<?= $cat['category_description'] ?>
</div>
</div>
<div class="discussions_right">
</div>
</div>
<?php endwhile; ?>
<?php else: ?>
<p>There are no posted categories available yet.</p>
<?php endif; ?>
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 have a project on which i need to implement pagination. I tried searching various time but couldn't find any satisfactory result. That's why I'm posting my question here --
This is Controller file IndexController.php
This is my indexAction, in which I'm trying to implement pagination -
public function indexAction() {
$this->_helper->layout->setLayout('layout');
//pagination
$page = $this->_request->getParam('page');
if (empty($page)) {
$page = 1;
}
$paginator = $this->_objCoupon->getOnePageOfOrderEntries($page);
$this->view->paginator = $paginator;
//pagination ends
$coupons = $this->_objCoupon->getAllcoupon();
$storage = new Zend_Auth_Storage_Session();
$dataUser = $storage->read();
$id = $dataUser->id;
//$id = $storage->id;
$arrCoupon = array();
if(count($coupons) > 0) {
$i= 0;
foreach($coupons as $couponArray) {
$arrCoupon[$i]["pid"] = $couponArray['id'];
$arrCoupon[$i]["title"] = $couponArray['partner_name'];
$arrCoupon[$i]["img"] = $couponArray['companylogo'];
$arrCoupon[$i]["value"] = $couponArray['coupon_value'];
$i++;
}
}
$this->view->arrCoupon = $arrCoupon;
$this->view->selectedcheckbox = $this->selectCheckboxes;
$this->view->id = $id;
$this->view->asd = 'all';
}
This is model file CouponModel.php
And this is my model function
public function getOnePageOfOrderEntries($page=1) {
//$paginator = $this->_coupon->getAllcoupon();
$query = "SELECT * FROM rechargecoupon WHERE online_offer = 'N' ORDER BY id ASC";
$paginator = new Zend_Paginator(
new Zend_Paginator_Adapter_DbTableSelect($query)
);
$paginator->setItemCountPerPage(20);
$paginator->setCurrentPageNumber($page);
return $paginator;
}
And in view I'm just trying to print paginator variable value for now.
This is View file index.phtml
<?php if (count($this->paginator)): ?>
<?php print_r($this->paginator); die; ?>
When I'm executing this file, I'm getting "Class Zend_Paginator_Adapter_DbTableSelect not found error".
You should have these variables in your action:
$currentPage = value obtained from URL, has to be >= 1
$itemsPerPage = hard coded value, ideally taken from configuration
$itemsCount = SELECT COUNT(*) FROM ... WHERE ...
$pagesCount = ceil($itemsCount / $itemsPerPage)
$items = SELECT * FROM ... WHERE ... LIMIT ($currentPage - 1) * $itemsPerPage, $itemsPerPage, these are items to be displayed, for example articles
When you set these variables in your action, you should pass them to your view and generate pagination from them, that means:
If pages count is larger than 1:
display pagination
generate pagination from 1 to $pagesCount = 1, 2, 3 ... 10
each generated pagination number should have associated URL to your action
If pages count is 1:
do not display pagination
First of all.
Correct to use
$query = $this->select()
->from('rechargecoupon')
->where('online_offer = ?', 'N')
->order('id ASC')
$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbTableSelect($query));
$paginator->setItemCountPerPage('50');
$paginator->setCurrentPageNumber($page);
This is in the model.
In view
<?php if ($this->paginator->getTotalItemCount() !== 0): ?>
// echo elements you need
<?php endif; ?>
<?php echo $this->paginationControl( $this->paginator, 'Sliding', 'pagination.phtml' ); ?>
pagination.phtml displays pagination.
in pagination.phtml
<?php if ($this->pageCount > 1): ?>
<div>
<!-- Previous page -->
<?php if (isset($this->previous)): ?>
<a href="<?php echo $this->url(array('page' => $this->previous)); ?>">
<span>< <?php echo 'previous'; ?></span>
</a>
<?php else: ?>
<span class="disabled">< <?php echo 'previous'; ?></span>
<?php endif; ?>
<!-- Page links -->
<?php foreach ($this->pagesInRange as $page): ?>
<?php if ($page != $this->current): ?>
<a href="<?php echo $this->url(array('page' => $page)); ?>">
<span><?php echo $page; ?></span>
</a>
<?php else: ?>
<?php endif; ?>
<?php endforeach; ?>
<?php if(!in_array($this->pageCount, $this->pagesInRange)): ?>
<a href="<?php echo $this->url(array('page' => $this->pageCount)); ?>">
<span><?php echo $this->pageCount; ?></span>
</a>
<?php endif;?>
<?php if (isset($this->next)): ?>
<a href="<?php echo $this->url(array('page' => $this->next)); ?>">
<span><?php echo 'next'; ?> ></span>
</a>
<?php else: ?>
<span class="disabled"><?php echo 'next'; ?> ></span>
<?php endif; ?>
</div>
<?php endif; ?>