email when images change, woocommerce product - image

I am attempting to send out an email anytime a woocommerce product has its images changed in any way.
I started off by attempting to get the $_POST of the image gallery, but I think I am calling it the wrong thing… I have tried the following:
$images = $_POST[‘image_ids’];
$images = $_POST[‘gallery_image_ids’];
Then I am comparing that value to the current image ids:
$oldImages = $product->get_gallery_image_ids();
If they do not match I am using wp_mail to send an email to various people.
I am doing all this inside a custom php function using:
add_action(‘pre_post_update’, ‘content_change_email’, 10, 2);
function content_change_email($post_ID, $data)
{
}
I assume the problem is originating with the
$images = $_POST[‘image_ids’];
$images = $_POST[‘gallery_image_ids’];
part of the code.
Can someone let me know what the correct meta field name for the gallery images is?

I solved my own problem…
I used a custom meta field to record the IDs for all the images, including the featured image then compared that to the current gallery images to see if they had changed, if they did then update the custom meta value with the new numbers and send an email to let people know the pictures changed.
code is as follows:
// send email when images change for a product
add_action( 'woocommerce_update_product', 'imagecheck_on_product_save', 10, 1 );
function imagecheck_on_product_save( $product_id ) {
$product = wc_get_product( $product_id );
// do something with this product
$metaImages = get_post_meta( $product_id, '_gallery_image_ids', true );
$currentImages = $product->get_gallery_image_ids();
$imageIDs = get_post_thumbnail_id( $product_id );
if ($imagesIDs != "" )
{
$imageIDs = $imageIDs . ", ";
foreach($currentImages as $value){
$imageIDs = $imageIDs . $value . ", ";
}
if ( $metaImages != $imageIDs ) {
update_post_meta( $product_id, '_gallery_image_ids', esc_attr( $imageIDs ) );
global $current_user;
wp_get_current_user();
$email = $current_user->user_email;
$lastuser = $current_user->user_firstname;
if ( $product->get_sku() != "" )
{
$memail = "<pre>USER: " . $lastuser . " made the following changes:</br>
Meta gallery images: " . $metaImages . "</br>
</br>
Actual gallery images: " . $imageIDs . "
" . $memail . "</pre>";
$headers = array('Content-Type: text/html; charset=UTF-8');
$subject = "PICTURES CHANGED - SKU: " . $product->get_sku();
$to = "(insert who you want to send to here)";
wp_mail( $to, $subject, $memail, $headers );
}
}
}
}

Related

How to use Ajax pager in Drupal7

I want to use ajax_pager in my block.
I've installed Libraries API and Ajax Pager API (as it described on the AP API page). But it's still not working.
When I use 'pager' instead of 'ajax_pager' it works.
What I'm doing wrong?
<?php
function latest_news_block_info() {
$blocks['latest_news_block'] = array(
// info: The name of the block.
'info' => t('Latest News'),
);
return $blocks;
}
function latest_news_block_view($delta = '') {
// The $delta parameter tells us which block is being requested.
switch ($delta) {
case 'latest_news_block':
// Create your block content here
$block['subject'] = t('Last news');
$query = new EntityFieldQuery();
//change news by the name of your content type
$entities = $query->entityCondition('entity_type', 'node')
->pager(5, 0)
->entityCondition('bundle', 'news')
->propertyOrderBy("created", "DESC")
->execute();
$content = "";
foreach($entities['node'] as $obj) {
$node = node_load($obj->nid);
$content .= "<img src='" .file_create_url($node->field_image['und'][0]['uri']) . "' width='200px' height='200px'>" . l($node->title, "node/" . $node->nid) . truncate_utf8($node->body['und'][0]['value'], 200, true, true) . '<br><hr>';
$block['content'] = $content;
}
break;
}
$pager = theme('ajax_pager', array('parameters' => array('selector' => 'block-system-main')));
$block['content'] .= $pager;
return $block;
}

checkout/session not returning order id while it is working on development site

I am working with magento and third party payment wallet Mobikwik. I got it working in my development site. But same code in production site does not return success page but return shopping cart empty after payment.
Path of file : community/wallet/controllers/Transactcontroller.php
$session = Mage::getSingleton('checkout/session');
$session->setQuoteId($session->getWalletQuoteId(true));
$walletConfig = Mage::getStoreConfig('payment/wallet');
$statuscode = $postdata['statuscode'];
$orderid = $postdata['orderid'];
$mid = $postdata['mid'];
$amount = $postdata['amount'];
$message = $postdata['statusmessage'];
$checksumReceived = $postdata['checksum'];
$all = "'" . $statuscode . "''" . $orderid . "''" . $amount . "''" . $message . "''" . $mid . "'";
if($checksumReceived != null){
$isChecksumValid = $this -> verifyChecksum($checksumReceived, $walletConfig['secret_key'], $all);
}
if($isChecksumValid){
// success
if ($this->_validateResponse()) {
Mage::getSingleton('checkout/session')->getQuote()->setIsActive(false)->save();
$order2 = Mage::getModel('sales/order')->loadByIncrementId($session->getLastRealOrderId());
$order1 = Mage::getModel('sales/order')->load($postdata['orderid']);
$total_amount = (double)$order2->getGrandTotal(); //// total amount from database for an order ////
if( ((double)$postdata['amount'] == (double)$order2->getGrandTotal()) AND ($session->getLastRealOrderId() == $postdata['orderid'])) {
// success code here and redirect to success page
else { // print error message }
$order2 is returning nothing but $order1 returning correct values.
Above code is working in development site. I found that problem is in production database.
Can anyone point me any correct direction!

magento custome api connection to economics

I am running an api for magento shop to connect to economics : please check this link for that api : https://github.com/tkjaergaard/Economic-PHP-SDK?_e_pi_=7%2CPAGE_ID10%2C1957533932
I just paste the folder in root directory and getting my order through
$orderId= Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order= Mage::getSingleton('sales/order')->loadByIncrementId($orderId);
My question is I need to include api folder in root director / vendor / autoload.php file for connection my extension....
So that when an new order is been placed in my shop the total order details will be automatically add to economics api...
Any idea on this... thanks in advance.
Create a new Order This method lets you create a newOrder to a specific Debtor.Theaddmethod on thelineobject accepts a array containing information on the product line. The array accepts the following elements:.Product: The product number.required.Description: The line description.optional*.Price: The unit price of the line.optional*.Qty: The quantity of the line.optional*.Unit: The Unit number to use.optional
<?php
require(Mage::getBaseDir().DS.'Economic-PHP-SDK-master'.DS.'vendor'.DS.'autoload.php');
use tkj\Economics\Client;
use tkj\Economics\Order\Order;
$client = new Client($agreementNumber,$userID, $password);
$order = new Order($client);
$debtorNumber = 101;
$newOrder =$order->create($debtorNumber, function($line)
{
$data = array(
"product" => 301,
"description" => "Description of line.",
"price" => 825.00,
"qty" => 5,
"unit" => 2);
$line->add($data);
});
class EconomicAPI_Model_Observer {
public function ordermigrate($observer) {
$orderId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order = Mage::getSingleton('sales/order')->loadByIncrementId($orderId);
// echo "order subtotal: ".$order->getSubtotal()."<br>";
// echo "shipping: ".$order->getShippingAmount()."<br>";
// echo "discount: ".$order->getDiscountAmount()."<br>";
// echo "tax: ".$order->getTaxAmount()."<br>";
// echo "grand total".$order->getGrandTotal()."<br><br><br>";
$to = 'karthickica#gmail.com';
$subject = 'Mail before Sale order place.';
$message = $orderId ;
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
mail($to, $subject, $message, $headers );
}
}

DOMPDF Multiple Documents Generated In One PDF

I am using DOMPDF to generate invoices.
1 invoice at time is perfect.
But i want to print (from a while) all invoices between date
all is perfect
But Dompdf print only the last invoice.
The dompdf code
require_once("dompdf_config.inc.php");
$date1 = "2008-01-01";
$date2 = "2009-01-01";
$user = "User_1";
$sql=mysql_query("SELECT * FROM invoices WHERE datum BETWEEN '$date1' AND '$date2' AND user='$user' ORDER BY nummer ");
while ($rows=mysql_fetch_array($sql))
{
$num=$rows[number];
$datum=$rows[data];
$pay=$rows[pay];
// Need to get the user info from other table
$Query2 = "SELECT * from user WHERE user='$user'";
while ($rows2=mysql_fetch_array($Result2))
{
$name = $rows2[name];
//ETC...
// Now we generate the html invoice
$html =
'<html><body>'.
//the invoice html
'</body></html>';
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
}
}
$dompdf->stream("Invoice.pdf");
I want to get all invoices ( sometimes 5, sometimes 50 ) in 1 pdf file.
How to ?
I close my whiles at end of files, but don't help.
Hope you can help.
The way your code is written right now you render your first document then don't do anything with it. So the second pass through the while loop will overwrite the first pass. There are a few ways to achieve what you want, but the easiest would be to compile all your HTML into a single document then render that.
Using your code as a start:
require_once("dompdf_config.inc.php");
$date1 = "2008-01-01";
$date2 = "2009-01-01";
$user = "User_1";
$invoices = array();
$sql=mysql_query("SELECT * FROM invoices WHERE datum BETWEEN '$date1' AND '$date2' AND user='$user' ORDER BY nummer ");
while ($rows=mysql_fetch_array($sql)) {
$num=$rows[number];
$datum=$rows[data];
$pay=$rows[pay];
// Need to get the user info from other table
$Query2 = "SELECT * from user WHERE user='$user'";
while ($rows2=mysql_fetch_array($Result2)) {
$name = $rows2[name];
//ETC...
// Force page break between invoices
if ( strlen( $html ) > 0 ) { $html .= '<div style="page-break-before: always;"></div>'; }
// Now we generate the html invoice
$invoices[] = '<!-- the html invoice -->';
}
}
$html = '<html><body>' . implode( '<div style="page-break-before: always;"></div>' , $invoices ) . '</body></html>';
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
$dompdf->stream("Invoice.pdf");

set a chosen image-file-input as a featured image from wp frontend

SCENARIO : I allow to create posts from front-end. The form also has four image upload fields. I use the code pasted below for image attachments and setting the post thumbnail.
//insert attachments
if ($_FILES) {
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$pid);
}
}
//attachment helper function
function insert_attachment($file_handler,$post_id,$setthumb='false') {
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK){ return __return_false();
}
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $file_handler, $post_id );
//set post thumbnail
if ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id); //you will need to comment out this line if you use my solution
return $attach_id;//you will need to comment out this line if you use my solution
}
The post-thumbnail/featured image that is set through this code is the LAST image that is uploaded. I tried a google search for "set post thumbnail from frontend wordpress" and grazed through a lot of articles but none came close to what I am asking here. Majority of threads I came across at SE in regards to front-end posting, either talks about setting the featured image or about multiple uploads. I have also checked all the suggested questions which were prompted, while I was writing this question just to make sure if it has been asked before.
If it matters, here is the html that is used in the form, pretty standard.
<input type="file" name="image-one" id="image-one"/>
<input type="file" name="image-two" id="image-two"/>
<input type="file" name="image-three" id="image-three"/>
REQUEST : It would be great if I could get a solution that helps to assign any chosen image-input-field as a featured-image but at this moment, at least what I need to set the FIRST image input to be set as a featured-image/post-thumbnail. Kindly suggest a solution.
Bottomline is that I do not have an issue with setting post-thumbnail
but question is about having a choice to choose any of the uploaded
images as post-thumbnail or at least the first image, instead of the
last image as set by the current code.
PROGRESS REPORT :
Never know if it would help in cracking this issue. But when I print_($newupload), I get the id eg. 54287 ,of the last-image-input attachment that is saved as post-thumbnail.
This thread suggests a way to set a featured-image with the first image found in the post so I thought of working on that idea. But the code does not seem to work either.
$attachments = get_children(array(
'post_parent' => $pid,
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'ID'
));
if ($attachments) {
foreach ($attachments as $attachment) {
set_post_thumbnail($pid, $attachment->ID);
break;
}
FINAL WORD : The code in the progress report momentarily gets the job done for me, that is.. setting the first image-file-input as a featured-image/post-thumbnail and I am not even sure if this is the best way to do this. I am still looking for a solution which could give a flexibility to choose any image-input-field as a featured-image. If you decide to use this feature remember to comment out the second last and third last lines from the original code.
Saving a post_meta with _thumbnail_id as meta_key and the attach_id as meta_value won't make that image a featured image, you can use wp_insert_attachment that will help you a lot in this. Make sure you read the codex and the examples there. The function should be used in conjunction with wp_update_attachment_metadata() and wp_generate_attachment_metadata() this way your feature image will be created properly by wordpress.
EDIT:
I've looked over your code and I'm gussing it's easier to use it then my schetch in this case. I've added a file count and a parameter to insert_attachment. Check this code let me know what happens.
Example:
<?php
//insert attachments
if ($_FILES) {
array_reverse($_FILES);
$i = 0;//this will count the posts
foreach ($_FILES as $file => $array) {
if ($i == 0) $set_feature = 1; //if $i ==0 then we are dealing with the first post
else $set_feature = 0; //if $i!=0 we are not dealing with the first post
$newupload = insert_attachment($file,$pid, $set_feature);
$i++; //count posts
}
}
//attachment helper function
function insert_attachment($file_handler,$post_id,$setthumb='false') {
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK){ return __return_false();
}
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $file_handler, $post_id );
//set post thumbnail if setthumb is 1
if ($setthumb == 1) update_post_meta($post_id,'_thumbnail_id',$attach_id);
return $attach_id;
}
?>
We can set post featured image from frontend using following function,
simple you need to call this function
post_imgs_update($new_post_id);
after creating new post. and add following function in functions.php
if ( ! function_exists( 'post_imgs_update' ) ) :
function post_imgs_update($new_post_id) {
$data = array();
$attachment_ids = array();
// code for save featured image
if( isset( $_POST['nonce'] ) && wp_verify_nonce( $_POST['nonce'], 'image_upload' ) ){ // here nonce text is "image_upload" you need to add in form
$files = reArrayFiles($_FILES['files']);
if(!empty($_FILES['files'])){
//$i = 0;
$set_featured_img = 0 ;
foreach( $files as $file ){
if( is_array($file) ){
$attachment_id = upload_user_file( $file, basename($file['name']) );
if ( is_numeric($attachment_id) ) {
if ($set_featured_img == '0') {
set_post_thumbnail($new_post_id, $attachment_id);
$set_featured_img++;
$attachment_ids[] = $attachment_id;
}
else{
$attachment_ids[] = $attachment_id;
}
}
}
}
//add to array
$mediaurl = array();
foreach ($attachment_ids as $img_id) {
$imgurl = wp_get_attachment_url( $img_id );
$image_gallery[$img_id] = $imgurl;
}
update_post_meta( $new_post_id, '_stw_property_multi_images', $image_gallery); // 2nd arg field key
}
}
else {
$data['status'] = false;
$data['message'] = __('Nonce verify failed','realestate');
}
return $new_post_id;
}
endif;
if ( ! function_exists( 'reArrayFiles' ) ) :
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
endif;
if ( ! function_exists( 'upload_user_file' ) ) :
function upload_user_file( $file = array(), $title = false ) {
require_once ABSPATH.'wp-admin/includes/admin.php';
$file_return = wp_handle_upload($file, array('test_form' => false));
if(isset($file_return['error']) || isset($file_return['upload_error_handler'])){
return false;
}else{
$filename = $file_return['file'];
$attachment = array(
'post_mime_type' => $file_return['type'],
'post_content' => '',
'post_type' => 'attachment',
'post_status' => 'inherit',
'guid' => $file_return['url']
);
if($title){
$attachment['post_title'] = $title;
}
$attachment_id = wp_insert_attachment( $attachment, $filename );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
if( 0 < intval( $attachment_id ) ) {
return $attachment_id;
}
}
return false;
}
endif;
function my_handle_attachment($file_handler,$post_id,$set_thu=false) {
$attachurlarray = array();
// check to make sure its a successful upload
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $file_handler, $post_id );
return $attach_id;
}

Resources