Wednesday, September 13, 2017

Wordpress- I want to add pagination list of categories

 <?php   
    $args = array(
   'parent' => 0,
   'hide_empty' => 0
 );

$categories = get_categories( $args );
echo $cat =  ceil(count( $categories )/5);   
 ?>
 <?php
  $j=0;
 $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
  $posts_per_page = 5;
$offset = ($posts_per_page * $paged) - 5 ;
$args = array(
'orderby' => 'name',
'parent' => 0,
'hide_empty'         => 0,
'number' => $posts_per_page,
'offset' => $offset,
'posts_per_page' => 5,
'paged' => $paged

//'exclude'            => '1,3,24,9'
);
$categories = get_categories( $args );
foreach ( $categories as $category ) {
$j++;
 //echo '<a href="' . get_category_link( $category->term_id ) . '">' .       $category->name . '</a><br/>';
 $catname = $category->name;
 $catttid = $category->term_taxonomy_id;
  //}
   ?>

<div class="row"><h3 class="cat-title"><?php echo $catname; ?></h3><hr  class="space" /></div>
  <?php } ?>
  </div></div>
   <!-- #main -->
  </div><!-- #primary -->
  <?php
  $big = 999999999; // need an unlikely integer
    echo '<div class="paginate-links">';
  echo paginate_links( array(
  'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
  'format' => '?paged=%#%',
  'prev_text' => __('<<'),
  'next_text' => __('>>'),
  'current' => max( 1, get_query_var('paged') ),
  'total' => $cat
     ) );
echo '</div>';
  ?>

Thursday, August 31, 2017

Magento- Cannot display image inserted by WYSIWYG editor

I finally solved the problem. The cause of the problem is unprocessed shortcodes in the html content, which is the {{ media url="..." }} statement. Before echo this statement, the html content should be process by the processor from helper "cms". Below is the code:


$html_content = $content_from_db['content'];
$html_content = Mage::helper('cms')->getPageTemplateProcessor()->filter($html_content);
echo $html_content;

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>';
              
                 }

Wednesday, July 26, 2017

Woocommerce- Change number or products per row to 3

Woocommerce- Change number or products per row to 3


We can add below filter in functions.php

// Change number or products per row to 3
add_filter('loop_shop_columns', 'loop_columns');
if (!function_exists('loop_columns')) {
    function loop_columns() {
        return 3; // 3 products per row
    }
}

Tuesday, July 25, 2017

Magento - How to show all products of a category in only one page

Magento - How to show all products of a category in only one page



I have found the solution in Magento backend,

it's like this :

Configuration > catalog > frontend > Allow All Products per Page > yes  :)

Magento- Customer attribute values by attribute ID

Magento- Customer attribute values by attribute ID


 <?php
    $valuesCollection = Mage::getResourceModel('eav/entity_attribute_option_collection')
    ->setAttributeFilter(161)
    ->load();


    foreach ($valuesCollection as $item) {

    $attr = Mage::getModel('eav/entity_attribute_option')
    ->getCollection()->setStoreFilter()
    ->join('attribute','attribute.attribute_id=main_table.attribute_id', 'attribute_code')
    ->addFieldToFilter('main_table.option_id',array('eq'=>$item->getId()))->getFirstItem();
    $procategorydata= $attr->getData();       
    ?>
    <option value="<?php echo $procategorydata['option_id'] ?>"><?php echo $procategorydata['value'] ?></option>
    <?php
    }
    ?>

Saturday, July 1, 2017

Woocommerce- Add custom field to “customer details” block in order email

/**
 * Add custom fields to emails
 */
add_filter('woocommerce_email_customer_details_fields', 'my_checkout_field_order_meta_fields', 40, 3 );
function my_checkout_field_order_meta_fields( $fields, $sent_to_admin, $order ) {
  $fields['custom_field_1'] = array(
    'label' => __( 'Vælg og bekræft din biltype' ),
    'value' => get_post_meta( $order->id, 'Vælg og bekræft din biltype', true ),
  );
  $fields['custom_field_2'] = array(
    'label' => __( 'Afgivet bestilling' ),
    'value' => get_post_meta( $order->id, 'Afgivet bestilling', true ),
  );
 
 
  return $fields;
}

WooCommerce – remove payment method from emails

add_filter( 'woocommerce_get_order_item_totals', 'custom_woocommerce_get_order_item_totals' );

function custom_woocommerce_get_order_item_totals( $totals ) {
  unset( $totals['payment_method'] );
  return $totals;
}

Saturday, June 10, 2017

Wordpress- Contact form 7 : Validate comma separated urls

WP- Contact form 7 : Validate comma separated urls

1. If in form field is  [textarea* yoururls]
2. If we will put the url comma seperated .

3. We can use below filter to custom validation in functions.php

add_filter( 'wpcf7_validate_textarea*', 'function_validate_urls', 20, 2 );
function function_validate_urls( $result, $tag ) {
    if ( 'yoururls' == $tag->name ) {
        $yoururls = isset( $_POST['yoururls'] ) ? trim( $_POST['yoururls'] ) : '';
        $error='noerror';
        $sepurl = explode(",",$yoururls);
        foreach($sepurl as $sep){
             $sep = preg_replace('/\s+/', '', $sep);
            if($sep!=''){
                if (filter_var($sep, FILTER_VALIDATE_URL)) {
                   // valid
                } else {
                    //invalid
                    $error= 'error';
                }
            }
        }
        if ( $error == 'error' ) {
           $result->invalidate( $tag, "Please check all urls in exact format." );
           // $result->invalidate( $tag, $error );
        }
    }

    return $result;
}

Thursday, April 27, 2017

JQuery- in body click div hide, when i click on div also it hide

<label id="label-search">Search</label>
<input id="search" style="display: none;" name="q" value="" type="search">


<script>
jQuery(document).ready(function() {
    jQuery("#label-search").click(function(e) {
        jQuery("#search").show();
        jQuery("#label-search").hide();
        e.stopPropagation();
    });

    jQuery(document).click(function(e) {
        if (!jQuery(e.target).is('#label-search, #search')) {
            jQuery("#search").hide();
            jQuery("#label-search").show();
        }
    });
});
</script

Wednesday, April 5, 2017

Wordpress- Ajax Pagination (How to implement pagination on a custom WP_Query Ajax ?)

How to implement pagination on a custom WP_Query Ajax

1. Load More link.

<a id="more_posts" href="#">Load More</a>


2. Javascript: - Put this at the bottom of the file.

<script type="text/javascript">

    var ajaxUrl = "<?php echo admin_url('admin-ajax.php')?>";
    var page = 1; // What page we are on.
    var ppp = 3; // Post per page

    $("#more_posts").on("click",function(){ // When btn is pressed.
        $("#more_posts").attr("disabled",true); // Disable the button, temp.
        $.post(ajaxUrl, {
            action:"more_post_ajax",
           // offset: (page * ppp) + 1,
            offset: (page * ppp),
            ppp: ppp
        }).success(function(posts){
            page++;
            $(".name_of_posts_class").append(posts); // CHANGE THIS!
            $("#more_posts").attr("disabled",false);
        });

   });

</script>

3. Put this in the functions.php file.

function more_post_ajax(){
    $offset = $_POST["offset"];
    $ppp = $_POST["ppp"];
    header("Content-Type: text/html");

    $args = array(
        'post_type' => 'post',
        'posts_per_page' => $ppp,
        'cat' => 1,
        'offset' => $offset,
    );

    $loop = new WP_Query($args);
    while ($loop->have_posts()) { $loop->the_post();
       the_content();
    }

    exit;
}

add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');


4. Njoy :)

Tuesday, March 28, 2017

PHP: Validation of US Phone numbers

<?php
class Validation {
    public $default_filters = array(

        'phone' => array(
            'regex'=>'/^\(?(\d{3})\)?[-\. ]?(\d{3})[-\. ]?(\d{4})$/',
            'message' => 'is not a valid US phone number format.'
        )
    );
    public $filter_list = array();

    function Validation($filters=false) {
        if(is_array($filters)) {
            $this->filters = $filters;
        } else {
            $this->filters = array();
        }
    }

    function validate($filter,$value) {
        if(in_array($filter,$this->filters)) {
            if(in_array('default_filter',$this->filters[$filter])) {
                $f = $this->default_filters[$this->filters[$filter]['default_filter']];
                if(in_array('message',$this->filters[$filter])) {
                    $f['message'] = $this->filters[$filter]['message'];
                }
            } else {
                $f = $this->filters[$filter];
            }
        } else {
            $f = $this->default_filters[$filter];
        }
        if(!preg_match($f['regex'],$value)) {
            $ret = array();
            $ret[$filter] = $f['message'];
            return $ret;
        }
        return true;
    }
}

//example usage
$validation = new Validation();
echo nl2br(print_r($validation->validate('phone','555-555-1212'),true));
echo nl2br(print_r($validation->validate('phone','(555)-555-1212'),true));
echo nl2br(print_r($validation->validate('phone','555 555 1212'),true));
echo nl2br(print_r($validation->validate('phone','555.555.1212'),true));
echo nl2br(print_r($validation->validate('phone','(555).555.1212'),true));
echo nl2br(print_r($validation->validate('phone','(555)---555.1212'),true));//will not match
?>

Saturday, March 18, 2017

Wordpress- Disable update notification for individual single plugin

/******/
/* Disable update notification for individual single plugin
/******/
 
 
 
function filter_plugin_updates( $value ) {
    unset( $value->response['akismet/akismet.php'] );
    return $value;
}
add_filter( 'site_transient_update_plugins', 'filter_plugin_updates' );

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') ;
?>

Sunday, October 16, 2016

Wordpress- How to Stay Logged in for Longer Periods

// Stay logged in for longer periods
add_filter( 'auth_cookie_expiration', 'keep_me_logged_in' );
function keep_me_logged_in( $expirein ) {
    return 31556926; // 1 year in seconds
}