magento catalog search not working - magento

I have to make custom catalog search. For this I have made a file in /var/www/magento/customsearch.php and put following code:
$searchText = 'test';
$query = Mage::getModel('catalogsearch/query')->setQueryText($searchText)->prepare();
$fulltextResource = Mage::getResourceModel('catalogsearch/fulltext')->prepareResult(
Mage::getModel('catalogsearch/fulltext'),
$searchText,
$query
);
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->getSelect()->joinInner(
array('search_result' => $collection->getTable('catalogsearch/result')),
$collection->getConnection()->quoteInto(
'search_result.product_id=e.entity_id AND search_result.query_id=?',
$query->getId()
)
);
print_r($collection->getData());
But the collection returns blank array.It update catalogsearch query table each time but not update catalogsearch result table. Please help.

I put your same code on my Magento website:
<?php
include "app/Mage.php";
Mage::app();
$searchText = 'test';
$query = Mage::getModel('catalogsearch/query')->setQueryText($searchText)->prepare();
$fulltextResource = Mage::getResourceModel('catalogsearch/fulltext')->prepareResult(
Mage::getModel('catalogsearch/fulltext'),
$searchText,
$query
);
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->getSelect()->joinInner(
array('search_result' => $collection->getTable('catalogsearch/result')),
$collection->getConnection()->quoteInto(
'search_result.product_id=e.entity_id AND search_result.query_id=?',
$query->getId()
)
);
print_r($collection->getData());
And got an array with three of my products. So I guess, check your setup? You have products right? With the keyword 'test' some where in the attribute values?

Related

How to set userid for products added to cart in magento?

I am adding configurable products in to cart using the below code.
$product_id = 123;
$qty = 1;
$product = Mage::getModel('catalog/product')->load($product_id);
$cart = Mage::getModel('checkout/cart');
$cart->init();
$superAttributeArray = array('151' => '3');
$params = array(
'product' => $product_id,
'qty' => $qty,
'super_attribute' => $superAttributeArray
);
$cart->addProduct($product, $params);
$cart->save();
this code works well and I can able to add the product in to cart. Tested the same in Database.
I want to map user id for the quote that was created.
products will be added only after loggging in.
When I add products with above code, customer_id field in 'sales_flat_quote' table is NULL. I want current logged in user id need to be set to this quote.
Can any one help me with this?
Try the below code.
if(Mage::getSingleton('customer/session')->isLoggedIn()) {
$customerData = Mage::getSingleton('customer/session')->getCustomer();
$customerId = $customerData->getId();
}
Let me know if you have any query
You should look at adding this to the current customer user session (it doesn't matter if they're logged in or not then)
...
$cart->addProduct($product, $params);
$session = Mage::getSingleton(
'core/session', array('name'=>'frontend')
);
$session->setLastAddedProductId($product->getId());
$session->setCartWasUpdated(true);

How can i update my products?

I want to update from my script the meta title, the meta description and the meta keywords for all of my products.
The meta title = the name of the product
The meta description = the short description of the product
The meta keywords is the meta keywords i've put from the category of the product.
I can loop and get the informations i want to make the update (except the meta keywords of the description) and after how i can make the update inside the loop ?
Thanks
<?php require_once 'app/Mage.php';
umask(0);
set_time_limit(0); // ignore php timeout
ignore_user_abort(true); // keep on going even if user pulls the plug*
while(ob_get_level())ob_end_clean(); // remove output buffers
ob_implicit_flush(true); // output stuff directly
//error_reporting(E_ALL);
/* not Mage::run(); */
Mage::app('default');
// get product collection (All product)
$storeId = Mage::app()->getStore()->getId();
$visibility = array(
Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH,
Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG);
$_productCollection = Mage::getResourceModel('catalog/product_collection')
->addAttributeToSelect('*')
->addAttributeToFilter('visibility', $visibility)
->setStoreId($storeId)
->addStoreFilter($storeId);
foreach ($_productCollection as $pro) { // loop each product
$meta_title = $pro['meta_title'];
$meta_description = $pro['meta_description'];
$name = $pro['name'];
$short_description = $pro['short_description'];
// I want to update the meta_title, meta_description, meta_keywords
// meta_description = short_description
// meta_title = name
// meta_keywords = meta keywords from the category of the product
}
?>
You can easy set keyword and description by using standard setters.
Inside foreach loop just use :
foreach ($_productCollection as $pro):
$product = Mage::getModel('catalog/product')->load($pro->getId());
$product->setMetaTitle('Product Title')
->setMetaKeyword('Product keywords')
->setMetaDescription('Product Description')
->save();
endforeach;
Try this,
foreach ($_productCollection as $pro):
$product = Mage::getModel('catalog/product')->load($pro->getId());
$cats = $product->getCategoryIds();
$meta_keys = '';
foreach ($cats as $category_id) {
$_cat = Mage::getModel('catalog/category')->load($category_id) ;
if($_cat->getMetaKeywords())
$meta_keys .= $_cat->getMetaKeywords().', ';
}
$product->setMetaTitle($pro->getName())
->setMetaKeyword($meta_keys)
->setMetaDescription($pro->getShortDescription())
->save();
endforeach;

Magento - Get product name for all languages

When reading all magento products for a export extension I've encountered a problem:
when trying to get the name of a product by using getName() on the loaded model you only get the active language name or if that is not set the default name of the product. But I need to get all product names for default, english, german, french, etc.
Does anyone have a solution for this problem or an idea how to solve it?
$model = Mage::getModel('catalog/product');
$collection = $model->getCollection();
foreach ($collection as $product) {
$id = $product->getId();
$model->load($id);
$name = $model->getName(); // gives you only the active language name / default name
}
Since you also want the default store, I'm only aware of one working way:
$aStoreHash = Mage::getModel('core/store')
->getCollection()
->setLoadDefault(true)
->toOptionHash();
$aName = array();
foreach ($aStoreHash as $iStoreId => $sStoreName) {
Mage::app()->setCurrentStore($iStoreId);
$oCollection = Mage::getModel('catalog/product')
->getCollection()
// Uncomment next line for testing if you have thousands of products
// ->addFieldToFilter('entity_id', array('from' => 1, 'to' => 5))
->addAttributeToSelect('name');
foreach ($oCollection as $oProduct) {
$aName[$oProduct->getId()][$iStoreId] = $oProduct->getName();
}
}
var_dump($aName);
If you don't need the default store, you could drop Mage::app()->setCurrentStore($iStoreId); and use ->addStoreFilter($iStoreId) on the collection instead.

Magento: Filter products by Status

I'm having some serious Magento issues here. As expected the following:
$products = Mage::getModel('catalog/category')->load($category_id)
->getProductCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('status', array('eq' => 1));
Will return all enabled products for my $category_id. However this:
$products = Mage::getModel('catalog/category')->load($category_id)
->getProductCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('status', array('eq' => 0));
Does not return disabled products. I can't seem to find a way to return disabled products, and I don't know why.
I've tried this:
Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($products);
Which was meant to have worked, but apparently may have been deprecated.
Does anyone know how to get all products in a category, enabled and disabled?
Don't worry, you simply got trapped by a very unusual constant definition^^. Just try:
$products = Mage::getModel('catalog/category')->load($category_id)
->getProductCollection()
->addAttributeToSelect('*')
->addAttributeToFilter(
'status',
array('eq' => Mage_Catalog_Model_Product_Status::STATUS_DISABLED)
);
For whatever reasons Varien decided to define this STATUS_DISABLED constant with a value of 2, instead of the more intuitive (and commonly used) value of 0.
I think you can do this by setting store to default like
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
make sure you save the current store value and set it back after doing the above.
Or by using a script from outside magento and invoke mage by
require_once '../app/Mage.php';
$app = Mage::app();
Mage::register('isSecureArea', true);
$products = Mage::getModel('catalog/category')->load($category_id)
->getProductCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('status', 1)
->addAttributeToFilter('visibility', 4)
->setOrder('price', 'ASC');
I haven't found an answer as such to my question above. But I have saved a lot of time by using a different method.
I exported a CSV of all the products in my Magento, deleted all columns except Category ID and SKU (this is all I needed), and then filtered that to return all the skus instead.
If it helps anyone here is the code -
<?php
$file = fopen('allprods.csv', 'r');
// You can use an array to store your search ids, makes things more flexible.
// Supports any number of search ids.
$id = array($_GET['id']);
// Make the search ids safe to use in regex (escapes special characters)
$id = array_map('preg_quote', $id);
// The argument becomes '/id/i', which means 'id, case-insensitive'
$regex = '/'.implode('|', $id).'/i';
$skus = array();
while (($line = fgetcsv($file)) !== FALSE) {
list($ids, $sku) = $line;
if(preg_match($regex, $ids)) {
$skus[] = $sku;
}
}
$count = count($skus);
$i = 1;
echo $category_id;
foreach ($skus as $sku){
echo $sku;
if($i != $count) { echo "`"; }
$i++;
}
This solution was created by using a previous topic about filtering CSVs, here
So for now, I can survive. however - an answer to this question is still needed!
Nothing works if catalog_flat_product is on in backend configuration->catalog.
try this..this will give all the products enabled and disabled ultimately
$collection = Mage::getResourceModel('catalog/product_collection'); //this will give you all products
foreach($collection as $col)
{
$var = Mage::getModel('catalog/product')->loadByAttribute('sku',$col->getSku());
echo"<pre>";print_r($var->getData());echo"</pre>";
}
its really simple and after this you can easily filter products by status

Magento programmatically remove product images

This must be a such a simple programming task that I absolutely cannot find any information about it on the net. Basically, I'm trying to DELETE product images. I want to delete all images from a product's media gallery. Can I do this without wading through a million lines of code for such a simple task?
Please note that I've already tried this:
$attributes = $product->getTypeInstance()->getSetAttributes();
if (isset($attributes['media_gallery'])) {
$gallery = $attributes['media_gallery'];
$galleryData = $product->getMediaGallery();//this returns NULL
foreach($galleryData['images'] as $image){
if ($gallery->getBackend()->getImage($product, $image['file'])) {
$gallery->getBackend()->removeImage($product, $image['file']);
}
}
}
This absolutely does not work. I'm trying to delete images during an import so that I do not keep accruing duplicates. Any help would be greatly appreciated.
Okay, this is how I finally fixed my problem.
if ($product->getId()){
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$items = $mediaApi->items($product->getId());
foreach($items as $item)
$mediaApi->remove($product->getId(), $item['file']);
}
This is the link that finally set my head straight: http://www.magentocommerce.com/wiki/doc/webservices-api/api/catalog_product_attribute_media
Too bad it's not as simple as $product->getImages(), eh?
In Magento 1.7.0.2 I use this code for remove all images from a product gallery:
//deleting
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$items = $mediaApi->items($product->getId());
$attributes = $product->getTypeInstance()->getSetAttributes();
$gallery = $attributes['media_gallery'];
foreach($items as $item){
if ($gallery->getBackend()->getImage($product, $item['file'])) {
$gallery->getBackend()->removeImage($product, $item['file']);
}
}
$product->save();
With code from Davids Tay answer, I got the error:
Fatal error: Uncaught exception ‘Mage_Eav_Model_Entity_Attribute_Exception’ with message ‘SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (base_xxx.catalog_product_entity_media_gallery_value, CONSTRAINT FK_CAT_PRD_ENTT_MDA_GLR_VAL_VAL_ID_CAT_PRD_ENTT_MDA_GLR_VAL_ID FOREIGN KEY (value_id) REFERENCES `catalog_prod)’
To remove all images from a product gallery:
$product = Mage::getModel('catalog/product')->load($id);
$mediaGalleryAttribute = Mage::getModel('catalog/resource_eav_attribute')->loadByCode($entityTypeId, 'media_gallery');
$gallery = $product->getMediaGalleryImages();
foreach ($gallery as $image)
$mediaGalleryAttribute->getBackend()->removeImage($product, $image->getFile());
$product->save();
During deleting of images I found one interesting thing. When you try this code:
$galleryData = $product->getMediaGallery(); //this returns NULL
Media gallery object depends on how your product was created, if:
$product = Mage::getModel('catalog/product')->loadByAttr('sku', $sku);
then media gallery will be empty, if:
$product = Mage::getModel('catalog/product')->load($id);
then media gallery is object and you can use this object to delete images from db.
To delete images from file system you have to add such code:
#unlink(Mage::getBaseDir('media') . '\catalog\product\' . $image['file']);
but if you want to change image and name it like previous image (image1.png replace with image1.png) in this case you will have browser caching issue.
Also you can try to load media gallery for product:
$product->getResource()->getAttribute('media_gallery')->getBackend()->afterLoad($product);
This is the code I finally decided to use for this task.
protected function _removeMediaGalleryImages(Mage_Catalog_Model_Product $product)
{
$mediaGalleryData = $product->getMediaGallery();
if (!isset($mediaGalleryData['images']) || !is_array($mediaGalleryData['images'])) {
return;
}
$toDelete = array();
foreach ($mediaGalleryData['images'] as $image) {
$toDelete[] = $image['value_id'];
}
Mage::getResourceModel('catalog/product_attribute_backend_media')->deleteGallery($toDelete);
}
Hopefully this answer isn't unwelcome, as it's technically not a solution achieved via Magento programming as you ask, but I have successfully purged all gallery images myself for the same purpose simply by truncating the relevant tables in Magento 1.4.2.0 (I believe it's the same table structure in 1.5 as well).
TRUNCATE TABLE `catalog_product_entity_media_gallery`
TRUNCATE TABLE `catalog_product_entity_media_gallery_value`
Then follow up by removing all the image files within the /media/catalog/product directory.
I did look for a way to do this programmatically myself, but found this much more efficient and have experienced no negative side effects.
Just use this code to create .php file and place it to root folder of magento.
<?php
require_once 'app/Mage.php';
Mage::app();
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
$products = Mage::getModel('catalog/product')->getCollection();
//->addAttributeToFilter('entity_id', array('gt' => 14000));
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
foreach($products as $product) {
$prodID = $product->getId();
$_product = Mage::getModel('catalog/product')->load($prodID);
$items = $mediaApi->items($_product->getId());
foreach($items as $item) {
$mediaApi->remove($_product->getId(), $item['file']);
}
}
?>
What About this
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$items = $mediaApi->items($product->getId());
$attributes = $product->getTypeInstance()->getSetAttributes();
$gallery = $attributes['media_gallery'];
foreach($items as $item){
if ($gallery->getBackend()->getImage($product, $item['file'])) {
$gallery->getBackend()->removeImage($product, $item['file']);
}
}
$product->save();
Fastest way to remove image,then follow below steps:
delete all records from
catalog_product_entity_media_gallery
catalog_product_entity_media_gallery_value'
table because magento is save all product image data at those table.
Then index from Index management from admin for set image black.
Then remove image from dir then goto Your magento dir at media/catalog/product and from this folder delete all file.
Another Process:
Andy Simpson,you need a script which is delete all product from your system which will delete from DB and file system.
Step1: Create a php at root direct of magento system which include Mage.php at first code.
require_once "YOURMAGENTODIR/app/Mage.php";
umask(0);
Step2: set current store is admin and set Developer mode
Mage::app('admin');
Mage::setIsDeveloperMode(true);
Step3: Get Product Collection and create a loop for get one product by one by one
$productCollection=Mage::getResourceModel('catalog/product_collection');
Step4: fetch product image by one and remove image one using below code:
$remove=Mage::getModel('catalog/product_attribute_media_api')->remove($product->getId(),$eachImge['file']);
FULL CODE:
<?php
require_once "YOURMAGENTODIR/app/Mage.php";
umask(0);
Mage::app('admin');
Mage::setIsDeveloperMode(true);
$productCollection=Mage::getResourceModel('catalog/product_collection');
foreach($productCollection as $product){
echo $product->getId();
echo "<br/>";
$MediaDir=Mage::getConfig()->getOptions()->getMediaDir();
echo $MediaCatalogDir=$MediaDir .DS . 'catalog' . DS . 'product';
echo "<br/>";
$MediaGallery=Mage::getModel('catalog/product_attribute_media_api')->items($product->getId());
echo "<pre>";
print_r($MediaGallery);
echo "</pre>";
foreach($MediaGallery as $eachImge){
$MediaDir=Mage::getConfig()->getOptions()->getMediaDir();
$MediaCatalogDir=$MediaDir .DS . 'catalog' . DS . 'product';
$DirImagePath=str_replace("/",DS,$eachImge['file']);
$DirImagePath=$DirImagePath;
// remove file from Dir
$io = new Varien_Io_File();
$io->rm($MediaCatalogDir.$DirImagePath);
$remove=Mage::getModel('catalog/product_attribute_media_api')->remove($product->getId(),$eachImge['file']);
}
}
If you want to remove more products like 1000 or 5000 then use bottom one with direct query.
Before try this one take backup of your database
<?php
require_once 'app/Mage.php';
umask(0);
Mage::app();
set_time_limit(0);
ini_set('display_error','1');
$resource = Mage::getSingleton('core/resource');
$connection = $resource->getConnection('core_write');
$id = 101;
$product = Mage::getModel('catalog/product')->load($id);
$q = "DELETE FROM `catalog_product_entity_media_gallery` where entity_id = '".$product->getId()."'";
$connection->query($q);
?>
Accessing the Database for such things is a bad idea.
You can delete images ( or reorder them by changing the 'position' value ) using the following snippet in a custom module ( for the sake of simplicity i'm using ObjectManager, but you should place ProductFactory and ProductRepositoryInterface in the constructor )
$objectManager = ObjectManager::getInstance();
//Get ProductFactory in order to instatiate the Product Object
$productFactory = $objectManager->get('\Magento\Catalog\Model\ProductFactory');
//We have to use ProductRepositoryInterface in order to save the changes bellow to the product
$productRepository = $objectManager->get('\Magento\Catalog\Api\ProductRepositoryInterface');
//Load a Product by ID in this case 1
$product = $productFactory->create()->load(1);
//Gets an array containing arrays representing each image in the gallery
$mediaGalleryEntries = $product->getMediaGalleryEntries();
//Here we delete every image, you can use conditions in foreach
foreach ($mediaGalleryEntries as $key => $imageEntry) {
unset($mediaGalleryEntries[$key]);
}
//Finally set the altered entries and save using productRepository
$product->setMediaGalleryEntries($mediaGalleryEntries);
$productRepository->save($product);
The code above tested in Magento 2.3 and it also removes images from the filesystem. You can use it to either delete or alter an entry ( change position, image roles etc )
To view each imageEntry you can access its data using $imageEntry->getData()
I had to do something similar not too long ago - needed to replace all product images during an import.
This link helped a lot: http://www.sharpdotinc.com/mdost/2010/03/02/magento-import-multiple-images-or-remove-images-durring-batch-import/
Hopefully it will give you a nudge in the right direction.
DELETE FROM catalog_product_entity_media_gallery WHERE value_id NOT IN (SELECT * FROM (SELECT MIN(value_id) FROM `catalog_product_entity_media_gallery` GROUP BY LEFT(value,17), entity_id having count(*) > 1) x)
why 17 ?
The expamle you have duplicate like this:
/0/0/000116810609_1.jpg
/0/0/000116810609_2.jpg
/0/0/000116810609_3.jpg
/0/0/000116810609_4.jpg
LEFT(value,17)
/0/0/000116810609
/0/0/000116810609
/0/0/000116810609
/0/0/000116810609
No they are duplicates ;)
Place the below script in magento root and execute
<?php
require_once("app/Mage.php");
umask(0);
Mage::app();
$ob = new Clean();
$ob->removemedia();
Class Clean {
function removemedia() {
$read = Mage::getSingleton('core/resource')->getConnection('core_read');
$select = $read->select()
->from('catalog_product_entity_media_gallery', '*')
->group(array('value_id'));
$flushImages = $read->fetchAll($select);
echo count($flushImages);
$array = array();
foreach ($flushImages as $item1) {
$array[] = $item1['value'];
}
$valores = $array;
$pepe = 'media' . DS . 'catalog' . DS . 'product';
$leer = $this->listDirectories($pepe);
foreach ($leer as $item) {
try {
$item = strtr($item, '\\', '/');
if (!in_array($item, $valores)) {
$valdir[]['filename'] = $item;
unlink('media/catalog/product' . $item);
}
} catch (Zend_Db_Exception $e) {
} catch (Exception $e) {
//Mage::log($e->getMessage());
}
}
}
function listDirectories($path) {
if (is_dir($path)) {
if ($dir = opendir($path)) {
while (($entry = readdir($dir)) !== false) {
if (preg_match('/^\./', $entry) != 1) {
if (is_dir($path . DS . $entry) && !in_array($entry, array('cache', 'watermark'))) {
$this->listDirectories($path . DS . $entry);
} elseif (!in_array($entry, array('cache', 'watermark')) && (strpos($entry, '.') != 0)) {
$this->result[] = substr($path . DS . $entry, 21);
}
}
}
closedir($dir);
}
}
return $this->result;
}
}

Resources