Sunday, July 29, 2018

Wordpress - print Custom Field with HTML content

HTML is printing as it is.


This was actually related to the view layer. Since that was not my business, I didn't care at first.
Turns out, that one has to us htmlspecialchars_decode in the templates, because the wordpress-api does htmlspecialchars on import.
The following code works fine
<? print htmlspecialchars_decode(get_custom_field('foo'));?>



Wednesday, July 4, 2018

jQuery- jQuery click event not working after adding class

Since the class is added dynamically, you need to use event delegation to register the event handler

$(document).on('click', "a.tabclick", function() {
   alert('COMES');   
});

Wednesday, August 9, 2017

Wordpress- Post Pagination Modifications (wp_link_pages)

Below code will show Next and Previous Links with the page count in between.
<?php

global $page, $pages;

// This shows the Previous link
wp_link_pages( array( 'before' => '<div class="page-link-next-prev">',
'after' => '', 'previouspagelink' => 'Previous', 'nextpagelink' => '',
'next_or_number' => 'next' ) );

// This shows the page count i.e. "1 of 5"
echo( $page.' of '.count($pages) );

// This shows the Next link
wp_link_pages( array( 'before' => '', 'after' => '</div>', 'previouspagelink' => '',
'nextpagelink' => 'Next', 'next_or_number' => 'next' ) );

?>


For infinite loop prev next, w can use below code- 

global $page, $pages;
                 if(count($pages) > 1){
                    
                  
                    
                echo '<div class="middle-pagination page-link-next-prev">';     
                if($page == 1){
                  
                    ?>
                     <a id="next" href="<?php the_permalink();?><?php echo count($pages);?>/" rel="prev">Prev</a>
                    <?php
                }
              
                wp_link_pages( array( 'before' => '',
                'after' => '', 'previouspagelink' => 'Prev', 'nextpagelink' => '',
                'next_or_number' => 'next' ) );

                // This shows the page count i.e. "1 of 5"
                echo '<span class="m-counts">';
                echo( $page.' of '.count($pages) );
                echo '</span>';

                // This shows the Next link
                wp_link_pages( array( 'before' => '', 'after' => '', 'previouspagelink' => '',
                'nextpagelink' => 'Next', 'next_or_number' => 'next' ) );
              
              
                if($page == count($pages)){
                  
                    ?>
                     <a id="next" href="<?php the_permalink();?>" rel="prev">Next</a>
                    <?php
                }
              
                echo '</div>';
              
                 }

Monday, November 14, 2016

PHP- function to correct all the images orientation in a given path or directory

<?php
/*
This function correct all the images orientation in a given path or directory.

Run:    php -r "require 'correctImageOrientation.php'; correctImageOrientation('test/');"
        or
        php -r "require 'correctImageOrientation.php'; correctImageOrientation('test/test1');"
        or
        php -r "require 'correctImageOrientation.php'; correctImageOrientation('test');"
*/
function correctImageOrientation($directory) {
   
    ini_set('memory_limit','2048M');
   
    $scanned_directory = array_diff(scandir($directory), array('..', '.'));
    echo "<pre>";
    print_r("scanned directory: \r\n");
    print_r($scanned_directory);
    echo "</pre>\r\n";
    foreach ($scanned_directory as &$file) {

        if (is_dir($directory."/".$file)) {
            correctImageOrientation($directory."/".$file);
        } else {                                   
            $filen = explode(".", $file);
            $ext = end($filen);
            try {

                $exif = @exif_read_data($directory."/".$file);

                $orientation = $exif['Orientation'];

                if (isset($orientation) && $orientation != 1){
                    switch ($orientation) {
                        case 3:
                        $deg = 180;
                        break;
                        case 6:
                        $deg = 270;
                        break;
                        case 8:
                        $deg = 90;
                        break;
                    }

                    if ($deg) {

                        // If png
                        if ($ext == "png") {
                            $img_new = imagecreatefrompng($directory."/".$file);
                            $img_new = imagerotate($img_new, $deg, 0);

                            // Save rotated image
                            imagepng($img_new,$directory.$file);
                        }else {
                            $img_new = imagecreatefromjpeg($directory."/".$file);
                            $img_new = imagerotate($img_new, $deg, 0);

                            // Save rotated image
                            imagejpeg($img_new,$directory."/".$file,80);
                        }
                    }
                    echo "<pre>";
                    print_r("image changed: \r\n");
                    print_r($directory."/".$file);
                    echo "</pre>\r\n";
                }

            } catch (Exception $e) {
                echo "error:";
                echo $e;
                echo "error";
            }
        }
    }
    unset($file);
}


correctImageOrientation('test/test1') ;
?>

Wednesday, August 17, 2016

Magento: Load record of my model by custom Field

Magento: Load record of my model by custom Field


$model = Mage::getModel('foo_bar/baz');
$model->load($id, 'field_name');

Wednesday, August 3, 2016

PHP- How to change the array key to start from 1 instead of 0 ?

how to change the array key to start from 1 instead of 0 ?

$newarr = array_combine(range(1, count($oldarr)), array_values($oldarr));

Wednesday, July 27, 2016

Magento: list all values of a single attribute

 $name='product_attribue_name';
    $attributeInfo =     Mage::getResourceModel('eav/entity_attribute_collection')->setCodeFilter($name)->getFirstItem();
    $attributeId = $attributeInfo->getAttributeId();
    $attribute = Mage::getModel('catalog/resource_eav_attribute')->load($attributeId);
    $attributeOptions = $attribute ->getSource()->getAllOptions(false);
    echo '<pre>'; print_r($attributeOptions);

Tuesday, July 26, 2016

Magento- get product collection by customer reviews

Magento- get product collection by customer reviews

<?php
$collection = Mage::getModel('review/review')
                ->getResourceCollection()
                ->addStoreFilter(Mage::app()->getStore()->getId())
                ->addFieldToSelect('*')
                ->addStatusFilter(Mage_Review_Model_Review::STATUS_APPROVED)
                ->addRateVotes();
$collection->getSelect()->group('entity_pk_value');
               
//echo $collection->getSelect();

print_r($collection->getData());

?>

Tuesday, March 22, 2016

Wordpress- Create Database Tables When on plugin actication hook

//create table               
function creat_table_on_actvation() {
         global $wpdb;
        $your_table_name = $wpdb->prefix . 'custom_contact_us';
     
        $sql = "CREATE TABLE IF NOT EXISTS " . $your_table_name . " (
          `id` int(11) NOT NULL AUTO_INCREMENT,
          `contact_name` varchar(255) NOT NULL,
          `contact_email` varchar(255) NOT NULL,
          `contact_subject` varchar(255) NOT NULL,
          `contact_message` text NOT NULL,
          `status` int(11) NOT NULL,
          `date_time` datetime NOT NULL,
          PRIMARY KEY (`id`)
        )";
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
}
// run the install scripts upon plugin activation
register_activation_hook(__FILE__,'creat_table_on_actvation');

PayPal - Adaptive Chained Payments

<?php

class PaypalTest {

public $api_user = "XXXXXXXXXXXXXXXXXXXXXX";
public $api_pass = "XXXXXXXXXXXXXXXXX";
public $api_sig = "XXXXXXXXXXXXXXXXXXXXXXX";
public $app_id = "APP-80W284485P519543T";
public $apiUrl = 'https://svcs.sandbox.paypal.com/AdaptivePayments/';
//public $paypalUrl="https://www.paypal.com/webscr?cmd=_ap-payment&paykey=";
public $paypalUrl="https://sandbox.paypal.com/webscr?cmd=_ap-payment&paykey=";
public $headers;

public function __construct(){
    $this->headers = array(
        "X-PAYPAL-SECURITY-USERID: ".$this->api_user,
        "X-PAYPAL-SECURITY-PASSWORD: ".$this->api_pass,
        "X-PAYPAL-SECURITY-SIGNATURE: ".$this->api_sig,
        "X-PAYPAL-REQUEST-DATA-FORMAT: JSON",
        "X-PAYPAL-RESPONSE-DATA-FORMAT: JSON",
        "X-PAYPAL-APPLICATION-ID: ".$this->app_id,
    );
  
    $this->envelope= array(
            "errorLanguage" => "en_US",
            "detailLevel" => "ReturnAll",
        );
  
  
}

public function getPaymentOptions($paykey){

//echo $paykey; die;
   $packet = array(
          "requestEnvelope" => $this->envelope ,
          "payKey" => $paykey
   );
 
   return $this->_paypalSend( $packet ,'GetPaymentOptions');
}

public function _paypalSend($data,$call){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $this->apiUrl.$call);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);
    $response = json_decode(curl_exec($ch),true);
    return $response;

}

public function splitPay(){


    // create the pay request
    $createPacket = array(
        "actionType" =>"PAY_PRIMARY",
        "applicationId" =>"APP-80W284485P519543T",
        "currencyCode" => "USD",
        "receiverList" => array(
            "receiver" => array(
               array(
                    "amount"=> "7.00",
                    "primary" => true,
                    "email"=>"primary-reciever@gmail.com"
                ),
                array(
                    "amount"=> "3.00",
                    "primary" => false,
                    "email"=>"secondary-reciever@gmail.com"
                ),
            ),
        ),
        "returnUrl" => "http://your-site-url/confirm.php",
        "cancelUrl" => "http://your-site-url//cancel.php",
        "requestEnvelope" => $this->envelope
    );

    $response = $this->_paypalSend($createPacket,"Pay");
  
  
    
    $paykey =  $response['payKey'];
    //echo '9999<pre>'; print_r($response);
  
    //SET payment details
  
     $detailsPacket=array(
"requestEnvelope" =>$this->envelope,
"payKey" => $paykey,
"receiverOptions" => array(
    array(
    "receiver" => array("email" => "primary-reciever@gmail.com"),
            "invoiceData" => array(
                "item" => array(
                    array(
                        "name" => "product1",
                        "price" => "7.00",
                        "identifier" => "p1"
                    ),
                   )
            )
    ),
    array(
        "receiver" => array("email" => 'secondary-reciever@gmail.com'),
        "invoiceData" => array(
        "item" => array(
            array(
                "name" => "product1",
                "price" => "3.00",
                "identifier" => "p1"
            ),
        )
      )
    ),
)
);


    $response1 = $this->_paypalSend($detailsPacket,"SetPaymentOptions");
  
  
    //$dets= $this->getPaymentOptions($paykey);
    $dets= $this->getPaymentOptions($paykey);
  
  

    $msg = $paykey;
  
    mail("amu02.aftab@gmail.com","My subject",$msg);
    //echo $this->paypalUrl.$paykey; die;
    header("Location: ".$this->paypalUrl.$paykey);
}

    public function _paymentExecute($url, $data){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);
        $response = json_decode(curl_exec($ch),true);
        return $response;
    }

}


if($_GET['exe_pay'] == 1){
  
    $url = "https://svcs.sandbox.paypal.com/AdaptivePayments/ExecutePayment";
  
    $payment = new PaypalTest();
    
    $packet = array(
          "requestEnvelope" => $payment->envelope,
          "payKey" => "AP-96831732KV5898725"
   );
    $response = $payment->_paymentExecute($url, $packet);
    echo '<pre>';print_r($response);
}elseif($_GET['get_info'] == 1){
    $url = "https://svcs.sandbox.paypal.com/AdaptivePayments/PaymentDetails";
  
    $payment = new PaypalTest();
  
    $packet = array(
          "requestEnvelope" => $payment->envelope,
          "payKey" => "AP-96831732KV5898725"
   );
    $response = $payment->_paymentExecute($url, $packet);
    echo '<pre>';print_r($response);
}else{
      
      
    $payment = new PaypalTest();
    $payment->splitPay();
  
}?>

PayPal - Adaptive parallel Payments

<?php
class PaypalTest {

public $api_user = "XXXXXXXXXXXXXXXXXXXXXXXXXXX";
public $api_pass = "XXXXXXXXXXXXXXXXXXXX";
public $api_sig = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
public $app_id = "APP-80W284485P519543T";
public $apiUrl = 'https://svcs.sandbox.paypal.com/AdaptivePayments/';
//public $paypalUrl="https://www.paypal.com/webscr?cmd=_ap-payment&paykey=";
public $paypalUrl="https://sandbox.paypal.com/webscr?cmd=_ap-payment&paykey=";
public $headers;

public function __construct(){
    $this->headers = array(
        "X-PAYPAL-SECURITY-USERID: ".$this->api_user,
        "X-PAYPAL-SECURITY-PASSWORD: ".$this->api_pass,
        "X-PAYPAL-SECURITY-SIGNATURE: ".$this->api_sig,
        "X-PAYPAL-REQUEST-DATA-FORMAT: JSON",
        "X-PAYPAL-RESPONSE-DATA-FORMAT: JSON",
        "X-PAYPAL-APPLICATION-ID: ".$this->app_id,
    );
    $this->envelope= array(
            "errorLanguage" => "en_US",
            "detailLevel" => "ReturnAll",
        );
}

public function getPaymentOptions($paykey){

   $packet = array(
          "requestEnvelope" => $this->envelope ,
          "payKey" => $paykey
   );
  
   return $this->_paypalSend( $packet ,'GetPaymentOptions');
}

public function _paypalSend($data,$call){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $this->apiUrl.$call);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);
    $response = json_decode(curl_exec($ch),true);
    return $response;

}
public function splitPay(){
    // create the pay request
    $createPacket = array(
        "actionType" =>"PAY",
        "currencyCode" => "USD",
        "receiverList" => array(
            "receiver" => array(
               array(
                    "amount"=> "2.00",
                    "email"=>"First Reciever Email"
                ),
                array(
                    "amount"=> "2.00",
                    "email"=>"Second Reciever Email"
                ),
            ),
        ),
        "returnUrl" => "http://your-site/confirm.php",
        "cancelUrl" => "http://your-site/cancel.php",
        "requestEnvelope" => $this->envelope
    );

    $response = $this->_paypalSend($createPacket,"Pay");
    $paykey =  $response['payKey'];
    //SET payment details
   
     $detailsPacket=array(
"requestEnvelope" =>$this->envelope,
"payKey" => $paykey,
"receiverOptions" => array(
    array(
    "receiver" => array("email" => "First Reciever Email"),
            "invoiceData" => array(
                "item" => array(
                    array(
                        "name" => "product1",
                        "price" => "2.00",
                        "identifier" => "p1"
                    ),
                   )
            )
    ),
    array(
        "receiver" => array("email" => 'Second Reciever Email'),
        "invoiceData" => array(
        "item" => array(
            array(
                "name" => "product1",
                "price" => "2.00",
                "identifier" => "p1"
            ),
        )
      )
    ),
)
);


    $response = $this->_paypalSend($detailsPacket,"SetPaymentOptions");
    $dets= $this->getPaymentOptions($paykey);
   
   
      header("Location: ".$this->paypalUrl.$paykey);
}
}


$payment = new PaypalTest();
$payment->splitPay();

?>