Google help on software/programming And Windows Tricks: 2015

helponsoftware

Friday 28 August 2015

image gallery restriction for any user in wordpress

function ml_restrict_media_library( $wp_query_obj ) {
    global $current_user, $pagenow;
    if( !is_a( $current_user, 'WP_User') )
        return;
    if( 'admin-ajax.php' != $pagenow || $_REQUEST['action'] != 'query-attachments' )
        return;
    if( !current_user_can('update_core') )
        //$wp_query_obj->set('author', $current_user->ID );
             $wp_query_obj->set('post__in',kk_ids());
    return;
}
function kk_ids(){
// $posts =query_posts(array('post_type'=>'kklibrary','posts_per_page'=>-1));
// foreach ($posts as $post):
// $post_thumbnail_id[] = get_post_thumbnail_id( $post->ID);
// endforeach;
// wp_reset_query();
return $post_thumbnail_id= array(248,249,250,251,252,253,254);
}
add_action('pre_get_posts','ml_restrict_media_library');

hide plugin from listing in wordpress

function mu_hide_plugins_network( $plugins ) {
    // let's hide akismet
    if( in_array( 'front-end-publishing/fepublishing.php', array_keys( $plugins ) ) ) {
        unset( $plugins['front-end-publishing/fepublishing.php'] );
    }
    return $plugins;
}

add_filter( 'all_plugins', 'mu_hide_plugins_network' );

Update the Image Uploaded in frontend or Regenerate Thumbnails

$fullsizepath = get_attached_file( $attach_id );
$metadata = wp_generate_attachment_metadata( $attach_id, $fullsizepath );
wp_update_attachment_metadata( $attach_id,  $metadata );

if ( is_wp_error( $metadata ) )
echo 'Images not upoaded Correctly Please try Again.';
if ( empty( $metadata ) )
echo 'Unknown failure reason.';

Add Any Charge in Checkout Woocommerce

add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge() {
  global $woocommerce;

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    $percentage = 0.01;
    $surcharge = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total ) * $percentage;   
    $woocommerce->cart->add_fee( 'Surcharge', $surcharge, true, '' );

}

Remove Duplicate Entry in Contact Form 7

add_filter( 'wpcf7_validate', 'email_already_in_db', 10, 2 );
function email_already_in_db ( $result, $tags ) {
// retrieve the posted email
$form = WPCF7_Submission::get_instance();
$email = $form->get_posted_data('email');
// if already in database, invalidate
if( is_already_submitted('Contact form 1' ,'email',$email ) )
$result->invalidate('email', 'Your email exists in our database');
// return the filtered value
return $result;
}
function is_already_submitted($formName, $fieldName, $fieldValue){
require_once(ABSPATH . 'wp-content/plugins/contact-form-7-to-database-extension/CFDBFormIterator.php');
$exp = new CFDBFormIterator();
$atts = array();
$atts['show'] = $fieldName;
$atts['filter'] = "$fieldName=$fieldValue";
$exp->export($formName, $atts);
$found = false;
while ($row = $exp->nextRow()) {
$found = true;
}
return $found;
}
Just set the field name, and form name in above function.

Friday 5 June 2015

Add Extra Button in CK Editor

editor.addCommand("mySimpleCommand", { // create named command
    exec: function(edt) {
        CKEDITOR.instances.ckeditor.setData("yes i am working");
      
    }
});

editor.ui.addButton('SuperButton', { // add new button and bind our command
    label: "Spine",
    command: 'mySimpleCommand',
    toolbar: 'insert',
    icon: 'https://avatars1.githubusercontent.com/u/5500999?v=2&s=16'
});

           editor.on( 'change', function( evt ) {
    // getData() returns CKEditor's HTML content.
    console.log( 'Total bytes: ' + evt.editor.getData());
});

Exclude any field from select query


CREATE TEMPORARY TABLE IF NOT EXISTS table2 AS (SELECT * FROM table1);

ALTER TABLE table2 DROP field_name;
SELECT * FROM table2;
DROP TABLE table2;

Tuesday 26 May 2015

Remove inline style in attachments

add_filter('wp_get_attachment_link', 'remove_img_width_height', 10, 1);

function remove_img_width_height($html) {
    $html = preg_replace( '/(width|height)=\"\d*\"\s/', "", $html );
    return $html;
}

Tuesday 28 April 2015

calculate the maximum length of palindrome by given any array of names or string

<?php
   function PalindromeLengthPuzzle($input1)
    {
$polin_array =array();
foreach ($input1 as $key => $value) {
  $res[]= substr($value,0,1);
}
print_r($res);
for($c=0;$c<=1000;$c++):
shuffle($res);

$result= implode('',$res);

if($result==strrev($result)){
 $polin_array[]=$result;   
}

endfor;
$polin_array=array_unique($polin_array);
print_r($polin_array);

foreach ($polin_array as $key => $value) {
    $val =strlen($value);
}
echo $val;
}

echo PalindromeLengthPuzzle(array('Bharti', 'Bharat','Brijesh','Bhavna','Anjit','Chand','Aushil'));
?>

Monday 27 April 2015

Wordpress Login by Any page

<?php
include('../impact windows/wp-load.php');
?>
<form method="post" action="http://localhost/anjit/impact%20windows/wp-login.php">
<input type="text" name="log">
<input type="password" name="pwd">
<input type="submit" name="sumit">
<input type="hidden" name="redirect_to" value="http://localhost/anjit/impact%20windows/wp-admin/edit.php?post_type=service" />

</form>

Image upload from frontend in wordpress

function insert_attachment() {
$uploaddir = wp_upload_dir();
$file = $_FILES['poster'];
$uploadfile = $uploaddir['path'] . '/' . basename( $file['name'] );

move_uploaded_file( $file['tmp_name'] , $uploadfile );
$filename = basename( $uploadfile );

$wp_filetype = wp_check_filetype(basename($filename), null );

$attachment = array(
    'post_mime_type' => $wp_filetype['type'],
    'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
    'post_content' => '',
    'post_status' => 'inherit',
    'menu_order' => $_i + 1000
);
$attach_id = wp_insert_attachment( $attachment, $uploadfile );
$fullsizepath = get_attached_file( $attach_id );
$metadata = wp_generate_attachment_metadata( $attach_id, $fullsizepath );
wp_update_attachment_metadata( $attach_id,  $metadata );

if ( is_wp_error( $metadata ) )
echo 'Images not upoaded Correctly Please try Again.';
if ( empty( $metadata ) )
echo 'Unknown failure reason.';

return $attach_id;
}

Wordpress Media uploader in frontend

<label for="image_url">Photo</label>
<input type="hidden" name="image_url" id="image_url" class="regular-text">
<input type="hidden" name="attachement_id" id="image_id" class="regular-text">
<div id="img_btn"><input type="button" name="upload-btn" id="upload-btn" class="button-secondary" value="Upload Image"></div>
<?php wp_nonce_field( 'my_image_upload', 'my_image_upload_nonce' ); ?>

<script type="text/javascript">
jQuery(document).ready(function($){
$('#upload-btn').click(function(e) {
e.preventDefault();
var image = wp.media({
title: 'Upload Image',
// mutiple: true if you want to upload multiple files at once
multiple: false
}).open()
.on('select', function(e){
// This will return the selected image from the Media Uploader, the result is an object
var uploaded_image = image.state().get('selection').first();
// We convert uploaded_image to a JSON object to make accessing it easier
// Output to the console uploaded_image
//console.log(uploaded_image);
var image_url = uploaded_image.toJSON().url;
var id = uploaded_image.toJSON().id;
// Let's assign the url value to the input field
$('#image_url').val(image_url);
$('#image_id').val(id);
});
});
});

</script>


USE below FUNCTION IN " functions.php"
wp_enqueue_media();

Wordpress login by user Role

add_action('login_form', 'wdm_login_form_role');
function wdm_login_form_role()
{
 ?>
<p><label for="user_role">Role<br>
<select name="role" style="flaot:left;width:100%;margin-bottom:10px;padding: 10px;">
<option value="publishers">Publishers</option>
<option value="advertisers">Advertisers</option>
</select></label>
<p>
 <?php
  }
add_filter('wp_authenticate_user','wdm_validate_login_role',10,2);
function wdm_validate_login_role($user, $password) {

   $ruser= get_user_by('login',$_POST['log']);

  if($ruser){
       if($ruser->roles[0]==$_POST['role']){
          return $user;
                   }
      else{
     return null;
      }
 }
}

Friday 27 February 2015

Get all chekbox value and set into textbox as an array

<script>
$('input:checkbox').on('change',function () {
      if(this.checked){
       var Val = (this.checked ? $(this).val() : "");
       var oldVal = $('#idoftextbox').val();
      $('#idoftextbox').val(Val+","+oldVal);
  }
else{

     var Val = $(this).val();
     var oldVal = $('#idoftextbox').val();
     data = removeValue(oldVal,Val);
      $('#activity_level').val(data);
}

  });

function removeValue(list, value) {
  list = list.split(',');
  list.splice(list.indexOf(value), 1);
  return list.join(',');
}

</script>

Friday 6 February 2015

Social Sharing by Url

http://www.facebook.com/sharer.php?u=

http://twitter.com/share?url=

http://www.linkedin.com/shareArticle?mini=true&url=

https://plus.google.com/share?url=

Thursday 15 January 2015

Open new Tab in I phone and Safari browser

<script>
function openTab(url) {
    // Create link in memory
    var a = window.document.createElement("a");
    a.target = '_blank';
    a.href = url;

    // Dispatch fake click
    var e = window.document.createEvent("MouseEvents");
    e.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    a.dispatchEvent(e);
};
</script>

after that you can call  this function to open any url like:

openTab('url');