Magento review for logged in customer on one product - php

I have a loop that shows all products that a customer has ordered, within that loop I want to pull out if the customer has rated that one product what rating they have given it. I think the problem is I need to use review/summary to display the rating?
$productsreviews = Mage::getModel('review/review')->getProductCollection()->addCustomerFilter(Mage::getSingleton('customer/session')->getCustomerId())->setDateOrder();
foreach ($productsreviews as $productsreview)
{
$product = Mage::getModel('catalog/product')->load($productsreview->getData('entity_pk_value'));
}
echo $product->getRating();
EDIT:Full Code
<?php
if (Mage::getSingleton('customer/session')->isLoggedIn()) {
/* Get the customer data */
$customer = Mage::getSingleton('customer/session')->getCustomer();
/* Get the customer's email address */
$customer_email = $customer->getEmail();
$customer_id = $customer->getId();
}
$collection = Mage::getModel('sales/order')->getCollection()->addAttributeToFilter('customer_email', array(
'like' => $customer_email
));
$uniuqProductSkus = array();
foreach ($collection as $order) {
$order_id = $order->getId();
$order = Mage::getModel("sales/order")->load($order_id);
$ordered_items = $order->getAllItems();
foreach ($ordered_items as $item)
{
if (in_array($item->getProduct()->getSku(), $uniuqProductSkus)) {
continue;
} else {
array_push($uniuqProductSkus, $item->getProduct()->getSku());
$_product = Mage::getModel('catalog/product')->load($item->getProductId());
$product_small_image_path = Mage::helper('catalog/image')->init($_product, 'small_image')->resize(200);
$product_thumbnail_path = Mage::helper('catalog/image')->init($_product, 'small_image')->resize(150);
$summaryData = Mage::getModel('review/review_summary')->load($item->getProductId());
echo "<li>";
echo "<div class='previous-name'><p><a style='color:black; font-weight:bold; font-size:14px;' href='" . $_product->getProductUrl() . "'>";
echo $item->getName() . "</a></p></div>";
echo "<div class='previous-image'><a href='" . $_product->getProductUrl() . "'>";
echo "<img src='" . $product_small_image_path . "' />";
echo "</a></div>";
echo "<div class='previous-rating'>";
echo "<p><a style='color:black; font-weight:bold; font-size:14px;' href='" . $_product->getProductUrl() . "#product_tabs_review_tabbed'>Review this beer now</a></p>";
echo $summaryData->getRatingSummary() . '% Would buy again <br/>';
echo "<div class='rating-box' style='float:left;'>";
echo "<div class='rating' style='width:" . $summaryData->getRatingSummary() . "%'></div></div>";
echo "<div class='previous-clear'></div></div>";
?>

review/summary will display the aggregated data. IIRC there's no method to pull out single review along with rating using the review model. This should give you the review object with associated rating:
$cReviews = Mage::getModel('review/review')->getResourceCollection()
->addStoreFilter($oProduct->getStoreId())
->addRateVotes()
->addStatusFilter(Mage_Review_Model_Review::STATUS_APPROVED)
->addEntityFilter('product', $oProduct->getId())
->setDateOrder()
->addFieldToFilter('customer_id', $yourCustomerId);
$cReviews->getSelect()->limit(1);
$oReview = $cReviews->getFirstItem();
Then you will have to calculate rating average for the single review:
if ( ($cRatings = $oReview->getRatingVotes()) && count($cRatings) ) {
$rAverage = array_sum($cRatings->getColumnValues('value')) / count($cRatings);
}

Related

How can i display my preg_match results in various divs so they can have multiple results under the correct heading?

Forgive me if this is simple but I have a for each loop that searches JSON data for results from a search. I then have some preg_match statements that will look at some of the tags within the JSON and if their is a match display the thumbnail in a div. and currently this all works. But it currently displays every result in its own Div and i want just five divs with multiple images within if there is a match.
foreach ($hits as $hit)
{
$target = $hit->metadata->baseName;
$target1 = $hit->metadata->cf_imageType;
if(preg_match("/_cm/i",$target)) {
echo '<div id="div5">';
echo '<h2>Creative</h2>';
echo "<img src='" . $hit->thumbnailUrl . "' alt='error'>";
echo $hit->metadata->baseName;
echo '</div>';
}
if(preg_match("/_SS/i",$target)) {
echo '<div id="div6">';
echo '<h2>Styled</h2>';
echo "<img src='" . $hit->thumbnailUrl . "' alt='error'>";
echo $hit->metadata->baseName;
echo '</div>';
}
if(preg_match("/_SH/i",$target)) {
echo '<div id="div7">';
echo '<h2>Group</h2>';
echo "<img src='" . $hit->thumbnailUrl . "' alt='error'>";
echo $hit->metadata->baseName;
echo '</div>';
}
if(preg_match("/still life/i",$target1) && preg_match("/_sm_00|_sd_00/i",$target)) {
echo '<div id="div8">';
echo '<h2>Cutout</h2>';
echo "<img src='" . $hit->thumbnailUrl . "' alt='error'>";
echo $hit->metadata->baseName;
echo '</div>';
}
if(preg_match("/worn/i",$target1)) {
echo '<div id="div9">';
echo '<h2>Worn</h2>';
echo "<img src='" . $hit->thumbnailUrl . "' alt='error'>";
echo $hit->metadata->baseName;
echo '</div>';
}
}
I cant quite figure out how to accomplish this, would it be the case of putting the results into an array and then displaying the results within the div?
Any help would be greatly appreciated.
You are right and answered the question yourself :)
Collect the results in a first step and create the markup in a second step. Something like this will do it:
$creative = [];
$styled = [];
/* ... */
function getHitInfos($theHit)
{
return [
"url" => $theHit->thumbnailUrl,
"name" => $theHit->metadata->baseName
];
}
function printResults($results, $title) {
echo '<div>';
echo '<h2>'.$title.'</h2>';
foreach ($results as $key => $val) {
echo "<img src='" . $val["url"] . "' alt='error'>";
echo $val["name"];
}
echo '</div>';
}
foreach ($hits as $hit)
{
$target = $hit->metadata->baseName;
$target1 = $hit->metadata->cf_imageType;
echo '<div>';
if(preg_match("/_cm/i",$target)) {
$creative[] = getHitInfos($hit)
}
if(preg_match("/_SS/i",$target)) {
$styled[] = getHitInfos($hit)
}
/* ... */
}
printResults($creative, "Creative");
printResults($styled, "Styled");
/* ... */
Disclaimer: My last contact with php is some years ago, but I hope you will see the point here.
(I also created some helping functions to DRY the code)

Dependency of HTML rendering on function's return value that executes later?

I have a function that prints "Our data" first and then inside a loop checks for all the data in the database and then prints the data.
However, if there is no data, it shouldn't print "Our data", how do I achieve this since "Our data" is already printed?
The layout is as follows :
<h1> Our Data </h1>
<p> <!-- DATA --> </p>
The function is as follows:
function cpt_info($cpt_slug, $field_name, $title) {
echo "<h1>Our" . $title . "</h1>"; //here I want to print our data
$args = array('limit' => -1);
$cpt = pods($cpt_slug, $args);
$page_slug = pods_v('last', 'url');
echo "<h1 class='projects-under-" . $cpt_slug . "'>" . $title . "</h1>";
if ($cpt->total() > 0) :
while ($cpt->fetch()) :
if (!strcasecmp($cpt->field('post_name'), $page_slug)) :
$data = $cpt->field($field_name);
foreach ((array) $data as $key => $value) {
if ($value != null) : //here I check whether data is empty
$url = wp_get_attachment_url(get_post_thumbnail_id($value['ID']));
echo "<div class='col-sm-3 col-xs-6'><div class='border-to-circle'>";
echo "<div class='circle-container' style='background: url(" . $url . ")center center, url(" . get_template_directory_uri() . '/images/rwp-banner.jpg' . ")center center;'><h4><a href='" . get_permalink($value['ID']) . "'>" . $value['post_title'] . "</a></h4></div>";
echo "</div></div>";
endif;
}
endif;
endwhile;
endif;
}
Something like below:
if(count($data)){
echo '<h1> Our Data </h1>';
}

ÅÄÖ (swedish characters) problems on update

I have some problems with displaying ÅÄÖ in jcart, I'm not very good at explaining but if you look here you'll see what I mean.
At first it all seems to work, but if you update the page or go to the checkout it doesn't. If you press "Ta bort" or add another item after updating the characters will be displayed correctly again. I use UTF-8 as charset and I've tried ISO-8859-1 which use to fix these problems, but instead it shows another symbol. Don't know exactly where the problem is so please tell me, if you have a clue, what you need more information about.
Looking at the demo may give you some ideas? Thanks!
To show the cart I have this: <?php $jcart->display_cart();?>
And here's some code from jcart.php (included file):
/**
* Process and display cart
*/
public function display_cart() {
$config = $this->config;
$errorMessage = null;
// Simplify some config variables
$checkout = $config['checkoutPath'];
$priceFormat = $config['priceFormat'];
$id = $config['item']['id'];
$name = $config['item']['name'];
$price = $config['item']['price'];
$qty = $config['item']['qty'];
$url = $config['item']['url'];
$add = $config['item']['add'];
// Use config values as literal indices for incoming POST values
// Values are the HTML name attributes set in config.json
$id = $_POST[$id];
$name = $_POST[$name];
$price = $_POST[$price];
$qty = $_POST[$qty];
$url = $_POST[$url];
// Optional CSRF protection, see: http://conceptlogic.com/jcart/security.php
$jcartToken = $_POST['jcartToken'];
// Only generate unique token once per session
if(!$_SESSION['jcartToken']){
$_SESSION['jcartToken'] = md5(session_id() . time() . $_SERVER['HTTP_USER_AGENT']);
}
// If enabled, check submitted token against session token for POST requests
if ($config['csrfToken'] === 'true' && $_POST && $jcartToken != $_SESSION['jcartToken']) {
$errorMessage = 'Invalid token!' . $jcartToken . ' / ' . $_SESSION['jcartToken'];
}
// Sanitize values for output in the browser
$id = filter_var($id, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_FLAG_STRIP_LOW);
$name = filter_var($name, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_FLAG_STRIP_LOW);
$url = filter_var($url, FILTER_SANITIZE_URL);
// Round the quantity if necessary
if($config['decimalPlaces'] === true) {
$qty = round($qty, $config['decimalPlaces']);
}
// Add an item
if ($_POST[$add]) {
$itemAdded = $this->add_item($id, $name, $price, $qty, $url);
// If not true the add item function returns the error type
if ($itemAdded !== true) {
$errorType = $itemAdded;
switch($errorType) {
case 'qty':
$errorMessage = $config['text']['quantityError'];
break;
case 'price':
$errorMessage = $config['text']['priceError'];
break;
}
}
}
// Update a single item
if ($_POST['jcartUpdate']) {
$itemUpdated = $this->update_item($_POST['itemId'], $_POST['itemQty']);
if ($itemUpdated !== true) {
$errorMessage = $config['text']['quantityError'];
}
}
// Update all items in the cart
if($_POST['jcartUpdateCart'] || $_POST['jcartCheckout']) {
$cartUpdated = $this->update_cart();
if ($cartUpdated !== true) {
$errorMessage = $config['text']['quantityError'];
}
}
// Remove an item
/* After an item is removed, its id stays set in the query string,
preventing the same item from being added back to the cart in
subsequent POST requests. As result, it's not enough to check for
GET before deleting the item, must also check that this isn't a POST
request. */
if($_GET['jcartRemove'] && !$_POST) {
$this->remove_item($_GET['jcartRemove']);
}
// Empty the cart
if($_POST['jcartEmpty']) {
$this->empty_cart();
}
// Determine which text to use for the number of items in the cart
$itemsText = $config['text']['multipleItems'];
if ($this->itemCount == 1) {
$itemsText = $config['text']['singleItem'];
}
// Determine if this is the checkout page
/* First we check the request uri against the config checkout (set when
the visitor first clicks checkout), then check for the hidden input
sent with Ajax request (set when visitor has javascript enabled and
updates an item quantity). */
$isCheckout = strpos(request_uri(), $checkout);
if ($isCheckout !== false || $_REQUEST['jcartIsCheckout'] == 'true') {
$isCheckout = true;
}
else {
$isCheckout = false;
}
// Overwrite the form action to post to gateway.php instead of posting back to checkout page
if ($isCheckout === true) {
// Sanititze config path
$path = filter_var($config['jcartPath'], FILTER_SANITIZE_URL);
// Trim trailing slash if necessary
$path = rtrim($path, '/');
$checkout = $path . '/gateway.php';
}
// Default input type
// Overridden if using button images in config.php
$inputType = 'submit';
// If this error is true the visitor updated the cart from the checkout page using an invalid price format
// Passed as a session var since the checkout page uses a header redirect
// If passed via GET the query string stays set even after subsequent POST requests
if ($_SESSION['quantityError'] === true) {
$errorMessage = $config['text']['quantityError'];
unset($_SESSION['quantityError']);
}
////////////////////////////////////////////////////////////////////////
// Output the cart
// Return specified number of tabs to improve readability of HTML output
function tab($n) {
$tabs = null;
while ($n > 0) {
$tabs .= "\t";
--$n;
}
return $tabs;
}
// If there's an error message wrap it in some HTML
if ($errorMessage) {
$errorMessage = "<p id='jcart-error'>$errorMessage</p>";
}
// Display the cart header
echo tab(1) . "$errorMessage\n";
echo tab(1) . "<form method='post' action='$checkout'>\n";
echo tab(2) . "<fieldset>\n";
echo tab(3) . "<input type='hidden' name='jcartToken' value='{$_SESSION['jcartToken']}' />\n";
echo tab(3) . "<table border='0'>\n";
echo tab(4) . "<thead>\n";
echo tab(5) . "<tr>\n";
echo tab(6) . "<th colspan='3'>\n";
echo tab(7) . "<div align='center'><span style='font-size:24px;' id='jcart-title'><br />VARUKORG</span> ($this->itemCount $itemsText) </div>\n";
echo tab(6) . "</th>\n";
echo tab(5) . "</tr>". "\n";
echo tab(4) . "</thead>\n";
// Display the cart footer
echo tab(4) . "<tfoot>\n";
echo tab(5) . "<tr>\n";
echo tab(6) . "<th colspan='3'>\n";
// If this is the checkout hide the cart checkout button
if ($isCheckout !== true) {
if ($config['button']['checkout']) {
$inputType = "image";
$src = " src='jcart/images/checkout.gif' alt='{$config['text']['checkout']}' title='' ";
}
echo tab(7) . "<input type='$inputType' $src id='jcart-checkout' name='jcartCheckout' class='jcart-button' value='{$config['text']['checkout']}' /> \n";
}
echo tab(7) . "<span id='jcart-subtotal'>{$config['text']['subtotal']}: <strong>" . number_format($this->subtotal, $priceFormat['decimals'], $priceFormat['dec_point'], $priceFormat['thousands_sep']) . " </strong></span>\n";
echo tab(6) . "</th>\n";
echo tab(5) . "</tr>\n";
echo tab(4) . "</tfoot>\n";
echo tab(4) . "<tbody>\n";
// If any items in the cart
if($this->itemCount > 0) {
// Display line items
foreach($this->get_contents() as $item) {
echo tab(5) . "<tr>\n";
echo tab(6) . "<td class='jcart-item-qty'>\n";
echo tab(7) . "<input name='jcartItemId[]' type='hidden' value='{$item['id']}' />\n";
echo tab(7) . "<input id='jcartItemQty-{$item['id']}' name='jcartItemQty[]' size='1' style='margin:0;padding:0;width:20px;' type='text' value='{$item['qty']}' />\n";
echo tab(6) . "</td>\n";
echo tab(6) . "<td class='jcart-item-name'>\n";
if ($item['url']) {
echo tab(7) . "<a href='{$item['url']}'>{$item['name']}</a>\n";
}
else {
echo tab(7) . $item['name'] . "\n";
}
echo tab(7) . "<input name='jcartItemName[]' type='hidden' value='{$item['name']}' />\n";
echo tab(6) . "</td>\n";
echo tab(6) . "<td class='jcart-item-price'>\n";
echo tab(7) . "<span>" . number_format($item['subtotal'], $priceFormat['decimals'], $priceFormat['dec_point'], $priceFormat['thousands_sep']) . "</span><input name='jcartItemPrice[]' type='hidden' value='{$item['price']}' />\n";
echo tab(7) . "<a class='jcart-remove' href='?jcartRemove={$item['id']}'>{$config['text']['removeLink']}</a>\n";
echo tab(6) . "</td>\n";
echo tab(5) . "</tr>\n";
}
}

How to display products under category [ data grouping ]

I am new to php-mysql. Can somebody help on the issue below? If so, please explain a bit so that I can learn. Thanks in advance.
$data=mysql_query("SELECT tbl_category.*, tbl_product.* FROM tbl_category LEFT JOIN tbl_product ON tbl_category.cat_id=tbl_product.cat_id ORDER BY tbl_category.cat_id");
$color="1";
while($fetch=mysql_fetch_array($data, MYSQL_ASSOC)){
if($fetch['cat_name'] != $category){ //this returns error: "Notice: Undefined variable: category in /.../filename.php on line [this line number]
$catdes = $fetch['pd_description'];
echo "<tr bgcolor='#A9F5F2'><td colspan=\"2\"><div align=\"center\"><br/><b>". $fetch['cat_name']."</b><br /><span class=\"itemdescription\">". $catdes."</div></div></td></tr>";
$category = $fetch['cat_name'];
}
$item = $fetch['pd_name'];
$desc = $fetch['pd_description'];
$price = $fetch['pd_price'];
if($color==1){
echo "<tr bgcolor='#FFFFFF'>";
echo "<td width=\"93%\"><div align=\"left\">";
echo $item . "<br /><span class=\"itemdescription\">";
echo $desc ;
echo "</div></td><td width=\"7%\" VALIGN=\"top\" ALIGN=\"right\"><div align=\"right\">";
echo $price ."</div></td><tr>";
$color="2";
}
else{
echo "<tr bgcolor='#F2F2F2'>";
echo "<td width=\"93%\"><div align=\"left\">";
echo $item . "<br /><span class=\"itemdescription\">";
echo $desc ;
echo "</div></td><td width=\"7%\" VALIGN=\"top\" ALIGN=\"right\"><div align=\"right\">";
echo $price ."</div></td><tr>";
$color="1";
}
}
That notice you received is the result of not declaring a variable before using it. It's always good practice to declare your variables before using them.
In your case you need to declare $category before comparing a value to it:
$category = '';
if($fetch['cat_name'] != $category){

I want to filter my Author avatar list by by User role

Here is my code. I only want to display The authors and exclude the rest of the user roles. Please help, I only have a few strands of hair left!!!!
function contributors() { global $wpdb;
$authors = $wpdb->get_results("SELECT ID, user_nicename from $wpdb->users ORDER BY display_name");
foreach($authors as $author)
{
echo "< li >";
echo "< a href=\"".get_bloginfo('url')."/?author=";
echo $author->ID; echo "\">";
echo get_avatar($author->ID, 125);
echo "";
echo '';
echo "< a href=\"".get_bloginfo('url')."/?author=";
echo $author->ID;
echo "\">"; the_author_meta('display_name', $author->ID);
echo "";
echo "";
echo ""; } }
Since I don't know how or where wordpress stores users roles, I suggest to use get_role() like this:
$realUser = wp_get_current_user();
foreach($authors as $author) {
set_current_user($author->ID);
if (get_role() != $authorRole) continue;
set_current_user($realUser->ID);
// ...
}
set_current_user($realUser->ID);

Categories