Wednesday, October 30, 2019

WordPress posts pagination(numeric)

WordPress posts numeric pagination:
-------------------------------------------------------------------------------------------------------------------
function ashique_all_trending_topics_blog_posts($atts, $content = null) {
  global $post;

  $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

  $blogs_arg2 = array(
      'posts_per_page'    => -1,
      'post_status'       => 'publish',
      'suppress_filters'  => true
  );
  $blogs_array2 = get_posts($blogs_arg2);
  $args = array(
    'posts_per_page'    => 12,
    'orderby'           => 'date',
    'order'             => 'DESC',
    'post_status'       => 'publish',
    'suppress_filters'  => true,
    'paged'             => $paged
  );
  $blogs_array = get_posts($args);
  for ($i = 0; $i < count($blogs_array); $i++) {
      //echo "<pre>";
      //print_r($blogs_array[$i]);
  }

  $output = '';

  $output .= '<div id="rp_trending_topics">';
 
  // $posts = get_posts($args); 
  foreach( $blogs_array as $post ) {   
    setup_postdata($post);
    if ( has_post_thumbnail() ) {
      $image_file_url = get_the_post_thumbnail_url();

      $upload_dir = wp_upload_dir();

      $file_name = explode('/', $image_file_url);
      $file_name = end($file_name);

      $data = file_get_contents($image_file_url);

      $new_image = $upload_dir['basedir'] .'/'. 'most-viewd-' . $file_name;
      file_put_contents($new_image, $data);

      $image_size = '300x200';
      $img_temp = explode("x", $image_size);
      $img_width = $img_temp[0];
      $img_height = $img_temp[1];

      $image = wp_get_image_editor( $new_image );
      if ( ! is_wp_error( $image ) ) {
        $image->resize( $img_width, $img_height, true );
        $image->save( $new_image );
      }
      $output .= '<div class="flex_column av_one_fourth"><div class="trending-post-container">';
      $image_tag_html = '<img class="wprp-post-image" src="' . $upload_dir['baseurl'] . '/' . 'most-viewd-' . $file_name . '" alt="" />';
    }
    else {
      $image_tag_html = '<img class="wprp-post-image" src="' . get_stylesheet_directory_uri() . '/images/default-image.jpg" />';
    }

    $num_words='12';
    $more='...';
    $excerpt = get_the_excerpt();
    $excerpt = wp_trim_words( $excerpt, $num_words , $more );

    $output .= '<article class="trending-image-with-content">
    <a class="single-image" href="'.get_the_permalink().'" title="">'.$image_tag_html.'</a>
    <div class="slide-content"><header class="entry-content-header">
    <h3 class="slide-entry-title entry-title" itemprop="headline">
    <a href='.get_the_permalink().' role="link" title="">'.get_the_title().'</a></h3></header>
    </div></article>';
    $output .= '<div class="rp_excerpt">'.$excerpt.'</div>';
    $output .= '<div class="rp_date_and_read_more"><span class="rp_date">'.get_the_date().'</span><a class="rp_read_more" href="'.get_the_permalink().'">Read More</a></div>';
    $output .= '</div></div>';
  }

  $output .= '</div>';

  $big = 999999999; // need an unlikely integer

  $count = count($blogs_array2);
  $offset = 12;

  $max = $count / $offset;
  if ( is_float($max) ) {
      $max = (int) $max + 1;
  }

  $mypagei = paginate_links(
    array(
      'base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
      'format' => '?paged=%#%',
      'current' => max(1, get_query_var('paged')),
      'total' => $max,
      'prev_text' => '«',
      'next_text' => '»'
    )
  );
  if ( $mypagei != '' ) {
    $output .= '<div class="pager">'.$mypagei.'</div>';  
  }

  wp_reset_postdata();
  return $output;
}

add_shortcode('ashique_all_trending_topics_blog_post', 'ashique_all_trending_topics_blog_posts');

/************************************* END ***********************************/

Monday, October 28, 2019

PHP script to export mysql database as sql file

PHP script to export mysql database as sql file:
-----------------------------------------------------------

<?php
//Enter your database information here and the name of the backup file
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$user = 'root';
$pass = '';
$host = 'localhost';
$db = 'dbname';
$dbs = [];

$db_conn = mysqli_connect($host, $user, $pass, $db);

$result = mysqli_query( $db_conn, "SHOW DATABASES" );
while ( $row = mysqli_fetch_array($result) ) {
    //echo $row[0]."<br>";
    array_push($dbs, $row[0]);
}

foreach ( $dbs as $value ) {
    $dir = dirname(__FILE__) . '/backupDB' . '/' . $value . '.sql';
    echo "<h3>Backing up database to {$dir}</h3>";
    exec("D:\\xampp1\\mysql\\bin\\mysqldump --user={$user} --password={$pass} --host={$host} {$value} --result-file={$dir} 2>&1", $output);
    var_dump($output);
}


*** Change the above code as per your DB info and put the code file into htdocs and run it.

Wednesday, August 28, 2019

Save image from url to disk and crop it in wordpress

Save image from url to disk and crop it in wordpress:
Follow the below code block to achieve this

$upload_dir = wp_upload_dir();

$file_name = explode('/', $first_image['src']); /* put your image url in this variable $first_image['src'] */
$file_name = end($file_name);

$data = file_get_contents($first_image['src']);

$new_image = $upload_dir['basedir'] .'/'. $file_name;
file_put_contents($new_image, $data);

$image_size = '320x190';
$img_temp = explode("x", $image_size);
$img_width = $img_temp[0];
$img_height = $img_temp[1];

$image = wp_get_image_editor( $new_image );
if ( ! is_wp_error( $image ) ) {
  $image->resize( $img_width, $img_height, true );
  $image->save( $new_image );
}


$output .= '<div class="wp_rss_retriever_image"><img' . $class . ' src="' . $upload_dir['baseurl'] . '/' . $file_name . '" alt="' . $title . '"></div>';

.:Happy Coding:.

Thursday, June 13, 2019

Scroll to target element while sticky menu is eating space

// Scroll code
jQuery(".target_container a").click(function(e) {
    e.preventDefault();
    var id =  jQuery(this).attr('href');
    jQuery('html, body').animate({         
        scrollTop: jQuery(id).offset().top-120
    }, 1000);
});

Friday, March 29, 2019

Retweet, replay and direct message with twitter api in laravel

Retweet, replay and direct message with twitter api in laravel:

First need to install thujohn/twitter package to your laravel app.
Then you need to logged in twitter to get access token.
With that access token you can do those below operations.

To retweet use the below function :

public function reTweet(Request $request)

{

        $tokens = Session::get('access_token');

        Twitter::reconfig($tokens);

        $input = $request->all();
        $postID = (string)$input['postId'];
        $status = $input['message'];

        $postStatus = ['format' => 'json', 'status' => $status];

        $result = Twitter::postRt($postID, $postStatus);
        $result = json_decode($result, true);

        return response()->json($result);
}

To reply use the below function :

public function reply(Request $request)
{
        $tokens = Session::get('access_token');
        Twitter::reconfig($tokens);

        $input = $request->all();
        $postID = (string)$input['id'];
        $status = '@'.$input['screen_name'].' '.$input['message'];

        $parameters = [
            'status' => $status,
            'in_reply_to_status_id' => $postID,
            'format' => 'json'
        ];

        $result = Twitter::postTweet($parameters);
        $result = json_decode($result, true);

        return response()->json(['success' => $result]);
}

To direct message to user use the below function :

public function sendMessage(Request $request)
{
        $tokens = Session::get('access_token');
        Twitter::reconfig($tokens);

        $test = Twitter::postDm([
            'user_id' => (string)$request->id,
            'screen_name' => $request->screen_name,
            'text' => $request->message
        ]);
        return response()->json($test);

}

Monday, September 24, 2018

File form submission by AJAX in custom plugin wordpress

Form (upload-admin.php):
<form id="form-id" name="form-name" method="post" enctype="multipart/form-data">
      <input type="file" id="file-id" name="file-name">
      <input type="submit" id="submit-btn" class="submit_btn" name="submit" value="Upload" />
      <input type="hidden" name="action" value="process_data" />
      <span class="validation-msg"></span>
</form>

<button id="main_submit_btn">Submit</button>

In main starting file add menu hook to call the html form:
function custom_admin() {
  include('upload-admin.php');
}

function now_menu() {
  add_management_page("My Title", "My Title", 1, "now-upload", "custom_admin");

}

function add_file_uploading_js() {
  wp_enqueue_script('my_custom_script', plugin_dir_url( __FILE__ ) . 'js/file_uploader.js', array('jquery'), false, true);
  // Localize the script with new data
  $data = array(
    'ajaxurl' => admin_url('admin-ajax.php')
  );
  wp_localize_script('my_custom_script', 'url_data', $data);
}

function process_data()
{
  global $wpdb, $channels;

  if (isset($_FILES)) {
      $uploaded = media_handle_upload($file, 0);
      $location = (get_attached_file($uploaded));
      if (is_wp_error($uploaded)) {
        wp_send_json_error("Error uploading file: " . $uploaded->get_error_message());
      }
      else {
        wp_send_json_success('Import Done!');
      }
  } else {
    wp_send_json_error('Please upload some files!');
  }
}

add_action('admin_menu', 'now_menu');
add_action('admin_enqueue_scripts', 'add_file_uploading_js');
add_action('wp_ajax_process_data', 'process_data');

file_uploader.js
// Jquery handle submission file form
(function ( $ ) {
$(document).ready(function(){
$(".submit_btn").css({'visibility':'hidden'});
var fileUploadParserUrl = url_data.file_upload_parser_url;

$("#main_submit_btn").click(function(event){
        // event.preventDefault();
        var fd = new FormData();
    var file = $('#FDH-form').find('input[type="file"]');
    var FDHfile = file[0].files[0];
    if (FDHfile === undefined) {
    $('.validation-msg').text('Please select all files! You might have missed one or more of xml file to select!');
    }
    else {
    $('.validation-msg').text('');
                        fd.append('file', FDHfile);
fd.append('action', 'process_data');
// disabled the submit button
        $("#main_submit_btn").prop("disabled", true);
        $('.spinner').css({"visibility":"visible"});
        // First clear xml_data table
        $.ajax({
            url: url_data.ajaxurl,
        data: fd,
        processData: false,
        contentType: false,
        dataType: 'json',
        type: 'POST',
            success: function (response) {
            $('.validation-msg-STH').text('STH_web_guide.xml Import Done!');
                // FINISH uploading and importing for ALL
            $("#main_submit_btn").prop("disabled", false);
                $('.spinner').css({"visibility":"hidden"});
            },
            error: function (e) {
                $("#main_submit_btn").prop("disabled", false);
                $('.spinner').css({"visibility":"hidden"});
            }
        });
    }
});
})(jQuery);

Sunday, September 23, 2018

File form submission by AJAX and PHP

Step 1: First have a look at the HTML form:
<form id="form" id="file-form" name="file_form" method="post" enctype="multipart/form-data">
<input type="file" id="file-input" name="file_input" value="" />
<input type="submit" id="submit-btn" class="submit_btn" name="submit" value="Upload" />
<span class="validation-msg"></span>
</form>

<button id="main_submit_btn">Upload</button>

Step 2: Then handle this form by JS(jQuery) code:
// Jquery handle submission of file
(function ( $ ) {
  $(document).ready(function(){
    $(".submit_btn").css({'visibility':'hidden'});
    $("#main_submit_btn").click(function(event){
      // event.preventDefault();
      var fd = new FormData();
      var file = $('#file-form').find('input[type="file"]');
      var myFile = file[0].files[0];
     
      if (myFile === undefined) {
$('.validation-msg').text('Please select file!');
      }
      else {
        $('.validation-msg').text('');
// disabled the submit button
        $("#main_submit_btn").prop("disabled", true);
        $('.spinner').css({"visibility":"visible"});
        $.ajax({
  url: process.php, // url to process
  data: fd,
  processData: false,
  contentType: false,
  dataType: 'json',
  type: 'POST',
  success: function (response) {
    // Upload succefull
    processFDH(fd, FDHfile);
  },
  error: function (e) {
    $("#main_submit_btn").prop("disabled", false);
    $('.spinner').css({"visibility":"hidden"});
  }
});
      }
  });
})(jQuery);

Step 3: process.php
if (isset($_FILES)) { 
   //
  if (check_upload_error($uploaded)) {
    echo json_encode("Error uploading file: " . $uploaded->get_error_message());
  }
  else {
    ajax_xml_import($file_content['name'], $location);
    echo json_encode('Import Done!');
  }
}
else {
  echo json_encode('Please upload some files!');

}

Wordpress debug log function

Wordpress error log code: if ( ! function_exists ( 'write_log' ) ) { function write_log ( $data ) { if ( defined ( '...