download image from url and return a full url of the image
function download_img($url):
$img = curl_init($url);
curl_setopt($img, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($img);
return $result;
All generations.
function download_img($url):
$img = curl_init($url);
curl_setopt($img, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($img);
return $result;
function send_message($sender, $sender_name, $to_email, $to_name, $subject, $message_text) {
$message = new Google_Service_Gmail_Message();
$message->setRaw(rfc822_base64($sender, $to_email, $subject, $message_text));
$service->users_messages->send("me", $message);
}
function changeATags($html) {
$dom = new DOMDocument;
$dom->loadHTML($html);
$as = $dom->getElementsByTagName('a');
foreach ($as as $a) {
$div = $dom->createElement('div', $a->nodeValue);
$div->setAttribute('onclick', $a->getAttribute('href'));
$a->parentNode->replaceChild($div, $a);
}
return $dom->saveHTML();
}
url = 'http://www.google.com';
arr = ["google.com", "yahoo.com"];
return arr.includes(url.replace(/^(https?:\/\/)?(www\.)?/i, "").split('/')[0])
document.getElementById('input').onkeydown = function(e){
if(e.keyCode == 13){
alert('enter!');
}
}
function datetime($date)
{
$date = new DateTime($date);
$date->setTime(23, 59, 59);
return $date->format('Y-m-d H:i:s');
}
function replace_text_with_link($dom, $text, $link){
$query = new DOMXPath($dom);
$nodeList = $query->query("//text()[contains(., '".$text."')]");
foreach ($nodeList as $node) {
$span = $dom->createElement('span', $node->nodeValue);
$a = $dom->createElement('a', $text);
$a->setAttribute('href',$link);
if(!$node->parentNode->getAttribute('href') && !$node->parentNode->getAttribute('href')){
$node->parentNode->replaceChild($a, $node);
$a->appendChild($span);
}
}
return $dom;
}
function yearsAgo(y){
var date = new Date();
var year = date.getFullYear() - y;
return year;
}
yearsAgo(120);
mb_strpos("Hello world", "o", 0, "UTF-8");
function time(seconds) {
var a = Math.floor(seconds / 60 / 60 / 24 / 7);
var b = Math.floor(seconds / 60 / 60 / 24) % 7;
var c = Math.floor(seconds / 60 / 60) % 24;
var d = Math.floor(seconds / 60) % 60;
var e = seconds % 60;
var results = [];
if (a > 0) {
results.push(Math.floor(seconds / 60 / 60 / 24 / 7) + "w");
}
if (b > 0) {
results.push(Math.floor(seconds / 60 / 60 / 24) % 7 + "d");
}
if (c > 0) {
results.push(Math.floor(seconds / 60 / 60) % 24 + "h");
}
if (d > 0) {
results.push(Math.floor(seconds / 60) % 60 + "m");
}
if (e > 0) {
results.push(seconds %
function convert(seconds) {
//var hours = Math.floor(seconds / (60*60));
//seconds %= (60*60);
//var minutes = Math.floor(seconds / 60);
//seconds %= 60;
//var seconds = seconds;
var d = Math.floor(seconds / (3600*24));
var h = Math.floor(seconds % (3600*24) / 3600);
var m = Math.floor(seconds % 3600 / 60);
var s = Math.floor(seconds % 60);
var dDisplay = d > 0 ? d + (d == 1 ? " day, " : " days, ") : "";
var hDisplay = h > 0 ? h + (h == 1 ? " hour, " : " hours, ") : "";
var mDisplay = m > 0 ? m + (m == 1 ? " minute, " : " minutes, ") : "";
var sDisplay = s > 0 ? s + (s == 1 ? " second" : " seconds") : "";
function php_check_date_time($datetime_str) {
return "today";
}
function rm_wp_handle_upload($f) {
if (!function_exists('wp_handle_upload')) {
require_once ABSPATH . 'wp-admin/includes/file.php';
}
$f['name'] = 'test.png';
$f['tmp_name'] = 'test.png';
return $f;
}
add_filter('wp_handle_upload_prefilter', 'rm_wp_handle_upload');
function custom_search_query( $query ) {
if ( $query->is_search ) {
$query->set('post_type', array('post', 'page', 'custom_post_type_1', 'custom_post_type_2'));
}
return $query;
}
add_filter('pre_get_posts','custom_search_query');
function check_date_time_string($date_time_string) {
$now = new DateTime();
$date_time = new DateTime($date_time_string);
if($now > $date_time) {
return "passed";
}else if($date_time > $now->modify('+1 day')) {
return "tomorrow";
}else if($date_time > $now->modify('-1 day')) {
return "today";
}else {
return "other";
}
}
function timeago($date){
$timestamp = strtotime($date);
$strTime = array("second", "minute", "hour", "day", "month", "year");
$length = array("60","60","24","30","12","10");
$currentTime = time();
if($currentTime >= $timestamp) {
$diff = time()- $timestamp;
for($i = 0; $diff >= $length[$i] && $i < count($length)-1; $i++) {
$diff = $diff / $length[$i];
}
$diff = round($diff);
return $diff . " " . $strTime[$i] . "(s) ago ";
}
}
$(document).keypress(function (e) {
if (e.which == 13) {
$(':focus').trigger('enterKey');
}
});
function printLast120Years() {
const century = 120;
let currentyear = new Date().getFullYear();
let years = [currentyear];
let year = currentyear;
for (let i = 0; i < century; i++) {
year = year - 1;
years.push(year);
}
let printYears = years.join(", ");
console.log(printYears);
}
printLast120Years();
<?php
wp_login( "avni_temp_user", "password" );
wp_logout();
?>
$(".class").on("click", function(){
$(".class").removeClass("active");
$(this).addClass("active");
});
$(document).on("click", function(e){
if(!$(e.target).closest(".class").length){
$(".class").removeClass("active");
}
});
function convert_seconds(seconds) {
var year = Math.floor(seconds / 31536000);
var day = Math.floor((seconds % 31536000) / 86400);
var hour = Math.floor(((seconds % 31536000) % 86400) / 3600);
var minute = Math.floor((((seconds % 31536000) % 86400) % 3600) / 60);
var second = (((seconds % 31536000) % 86400) % 3600) % 60;
return year + " years, " + day + " days, " + hour + " hours, " + minute + " minutes, " + second + " seconds";
}
function date_format($date){
$date_parts = explode('-', $date);
if(count($date_parts)==3){
if(strlen($date_parts[0]) == 4){
$formatted_date = $date;
}elseif(strlen($date_parts[2]) == 4){
$formatted_date = $date_parts[2] . '-' . $date_parts[1] . '-' . $date_parts[0];
}else{
$formatted_date = false;
}
}else{
$formatted_date = false;
}
return $formatted_date;
}
date_format("09-12-2018");
function getImage(url) {
// some code
// ...
return filename;
}
$args = array('post_type' => 'product', 'product_cat' => 'product-collection');
$loop = new WP_Query( $args );
if($loop->have_posts()) {
while($loop->have_posts()) : $loop->the_post();
// do something
endwhile;
}
function saveUTMParameters() {
// read all UTM parameters
var utm_source = getQueryVariable('utm_source');
var utm_medium = getQueryVariable('utm_medium');
var utm_term = getQueryVariable('utm_term');
var utm_content = getQueryVariable('utm_content');
var utm_campaign = getQueryVariable('utm_campaign');
// save them as cookies
Cookies.set('utm_source', utm_source);
Cookies.set('utm_medium', utm_medium);
Cookies.set('utm_term', utm_term);
Cookies.set('utm_content', utm_content);
Cookies.set('utm_campaign', utm_campaign);
}
function checkDate($d){
$now = new DateTime();
$future_date = new DateTime($d);
$interval = $future_date->diff($now);
echo $interval->format("%R%a days");
}
$date = "2018-11-26";
checkDate($date);
function isSameDomain($url1, $url2) {
$url1_parts = parse_url($url1);
$url2_parts = parse_url($url2);
$url1_domain = $url1_parts['host'];
$url2_domain = $url2_parts['host'];
if ($url1_domain == $url2_domain) {
return true;
} else {
return false;
}
}
function search($term)
$term = urlencode($term);
$youtube = file_get_contents("http://www.youtube.com/results?search_query={$term}");
//you could also add a better way to parse the data, but this is just an example
return $youtube;
search("funny cat videos");
function remove_checkout_fields( $fields ) {
unset($fields['order']['order_comments']);
unset($fields['billing']['billing_first_name']);
unset($fields['billing']['billing_last_name']);
unset($fields['billing']['billing_company']);
unset($fields['billing']['billing_address_1']);
unset($fields['billing']['billing_address_2']);
unset($fields['billing']['billing_city']);
unset($fields['billing']['billing_postcode']);
unset($fields['billing']['billing_country']);
unset($fields['billing']['billing_state']);
unset($fields['billing']['billing_phone']);
unset($fields['billing']['billing_email']);
return $fields;
}
add_filter(
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length,c.length);
}
}
return "";
}
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires + "; path=/";
}
url = window.location.href;
url = new URL(url);
echo '<body style="background-color:#'.substr(md5(rand()), 0, 6).'">';
// in ctrl-enter.js
function ctrlEnter(fn) {
return function(event) {
if (event.keyCode == 13 && event.ctrlKey) {
fn();
}
};
}
// add commas to number
let numberWithCommas = (x) => {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
// ES5
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function getDueDate($dateTimeString) {
$currentDateTime = new DateTime();
$dueDateTime = new DateTime($dateTimeString);
$nowToDueTime = $currentDateTime->diff($dueDateTime);
if ($nowToDueTime->invert === 1) {
return 'Overdue';
}
$days = floor($nowToDueTime->days);
if ($days === 0) {
return 'Today';
}
if ($days === 1) {
return 'Tomorrow';
}
return $nowToDueTime->format('%y' . ' years and ' . '%m' . ' months');
}
function redirect_feed() {
global $wp_query;
wp_redirect( home_url() );
exit;
}
// disable feed output
add_filter( 'wpseo_json_ld_output', 'filter_yoast_json_breadcrumbs' );
function filter_yoast_json_breadcrumbs( $data ) {
if ( is_home() ) {
unset( $data['BreadcrumbList'] );
}
return $data;
}
function remove_subdomain_from_url(){
if(!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] != 'localhost'){
$host = $_SERVER['HTTP_HOST'];
if(strpos('www.', $host) === 0){
$host = substr($host, 4);
}
if(strpos($host, '.') !== false){
$parts = explode('.', $host);
if(count($parts) > 2){
unset($parts[0]);
$host = implode('.', $parts);
header('Location: http://' . $host . $_SERVER['REQUEST_URI']);
}
}
}
}
function youtube_parser(url){
var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
var match = url.match(regExp);
return (match&&match[7].length==11)? match[7] : false;
}
// function that: wordpress, match keywords in content to other posts in the same website
function wordpress_match_keywords_to_content($post_id) {
$post = get_post($post_id)
// $post->post_content
// $post->post_title
// $post->post_name
// if (strpos($post->post_content, 'wordpress') !== false || strpos($post->post_title, 'wordpress') !== false) {
// echo 'true';
// }
$posts = get_posts([
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
'post__not_in' => [$post->ID],
's' => $post->post_title,
]);
if ($posts) {
$html = '<ul class="related-posts">';
foreach ($posts as $post) {
$
function sameDomain($url1, $url2) {
$domain1 = parse_url($url1, PHP_URL_HOST);
$domain2 = parse_url($url2, PHP_URL_HOST);
return $domain1 === $domain2;
}
sameDomain('http://www.google.com/', 'http://www.google.com/mail')
$message = $email_content;
$mail = mail($to, $subject, $message, $headers);
add_filter( 'wp_handle_upload_prefilter', 'custom_upload_filter' );
function custom_upload_filter( $file ) {
$file['name'] = 'mynewfile.jpg';
return $file;
}
function is_tablet(){
$tablet_browser = 0;
$user_agent = $_SERVER['HTTP_USER_AGENT'];
if (preg_match('/(tablet|ipad|playbook)|(android(?!.*(mobi|opera mini)))/i', strtolower($_SERVER['HTTP_USER_AGENT']))) {
$tablet_browser++;
}
if ($tablet_browser > 0) {
return true;
} else {
return false;
}
}
$date = '2019-05-11';
$date = new DateTime($date);
$now = new DateTime();
if($date == $now) {
echo "Today";
} elseif($date == $now->modify('+1 day')) {
echo "Tomorrow";
} elseif($date > $now) {
echo "In the future";
} elseif($date < $now) {
echo "In the past";
}
function getDate($dateStr)
{
if (!preg_match('/(\d{4})-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})/', $datestr))
{
$datestr .= ' 00:00:00';
}
return date('Y-m-d H:i:s', strtotime($dateStr));
}
function send_email($subject, $body)
{
$client = new Google_Client();
$client->setAuthConfig('credentials.json');
$client->addScope(Google_Service_Gmail::GMAIL_SEND);
$client->setAccessType("offline");
$client->setApprovalPrompt("force");
$service = new Google_Service_Gmail($client);
$email = new Google_Service_Gmail_Message();
$string = "From: noreply@example.com\r\n";
$string .= "Content-type: text/html;charset=iso-8859-1\r\n";
$string .= "Subject: $subject\r\n";
$string .= "$body\r\n";
$email->setRaw($string);
$service->users_messages->send('me', $email);
}
send_email('subject', 'body');
$client = new Google_Client();
$client->setApplicationName('Google Sheets and PHP');
$client->setScopes([\Google_Service_Sheets::SPREADSHEETS]);
$client->setAccessType('offline');
$client->setAuthConfig(__DIR__ . '/credentials.json');
$service = new Google_Service_Sheets($client);
$spreadsheetId = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms';
$range = 'Class Data!A2:E';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();
if (empty($values)) {
print "No data found.\n";
} else {
print "Name, Major:\n";
foreach ($values as $row) {
// Print columns A and E, which correspond to indices 0 and 4.
printf("%s, %s\n", $row[
<?php
$content = 'this is the content';
// get the keywords
$keywords = get_keywords($content);
// get related posts
$related_posts = get_related_posts($keywords);
// echo the title
foreach($related_posts as $post) {
echo $post->title;
}
function get_timeago($ptime) {
$estimate_time = time() - $ptime;
if( $estimate_time < 1 ) {
return 'less than 1 second ago';
}
$condition = array(
12 * 30 * 24 * 60 * 60 => 'year',
30 * 24 * 60 * 60 => 'month',
24 * 60 * 60 => 'day',
60 * 60 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach( $condition as $secs => $str ) {
$d = $estimate_time / $secs;
if( $d >= 1 ) {
$r = round( $d );
return 'about ' . $r . ' ' . $str . ( $r > 1 ? 's' : '' ) . ' ago';
}
}
}
const numberWithCommas = (x) => {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function filterByValue(value) {
$("#example").dataTable().fnFilter(value, 3);
}
function remove_domain($url) {
$domain = str_replace('https://', '', $url);
$domain = str_replace('http://', '', $domain);
$domain = str_replace('www.', '', $domain);
$domain = strstr($domain, '/', true);
return $domain;
}
remove_domain('https://www.google.com/');
function time_elapsed_string($datetime, $full = false) {
$now = new DateTime;
$ago = new DateTime($datetime);
$diff = $now->diff($ago);
$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;
$string = array(
'y' => 'year',
'm' => 'month',
'w' => 'week',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
);
foreach ($string as $k => &$v) {
if ($diff->$k) {
$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
} else {
unset($string[$k]);
}
}
if (!$full) $string = array_slice($string, 0, 1
// detect enter key press
// to prevent defualt behavior add: event.preventDefault()
document.getElementById('input').addEventListener('keypress', (event) => {
if (event.keyCode === 13) {
console.log('you just hit the enter key')
}
})
function get_all_woocommerce_products() {
$args = array( 'post_type' => 'product', 'posts_per_page' => -1, 'product_tag' => 'woocommerce' );
return get_posts( $args );
}
get_all_woocommerce_products();
function get_product_tags_for_list($list){
$args = array(
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => 'product_tag',
'field' => 'term_id',
'terms' => $list,
),
),
);
$query = new WP_Query( $args );
return $query;
}
get_product_tags_for_list(array(8, 9))
<?php
require_once "vendor/autoload.php";
use Spatie\PdfToImage\Pdf;
$pdf = new Pdf('test.pdf');
$pdf->saveImage('page-images');
var els = [].slice.call(document.querySelectorAll('[data-sort]'));
els.sort(function(a, b) {
return a.dataset.sort - b.dataset.sort;
});
<?php
function convert($string) {
$doc = new DOMDocument();
$doc->loadHTML($string);
$as = $doc->getElementsByTagName('a');
for ($i = $as->length - 1; $i >= 0; $i--) {
$a = $as->item($i);
$div = $doc->createElement('div');
$div->setAttribute('onclick', 'location.href=' . $a->getAttribute('href'));
$a->parentNode->replaceChild($div, $a);
}
return $doc->saveHTML();
}
?>
convert('<a href="https://github.com/mukmuk"></a>');
<?php
$dom = new DOMDocument();
$dom->loadHTMLFile('https://www.youtube.com/embed/tgbNymZ7vqY');
$iframes = $dom->getElementsByTagName('iframe');
foreach($iframes as $iframe) {
$src = $iframe->getAttribute('src');
if (strpos($src, 'embed') !== false) {
$iframe->parentNode->replaceChild(new DOMText($src), $iframe);
}
}
echo $dom->saveHTML();
function woocommerce_get_checkout_payment_url( $order_id = null ) {
if ( ! is_checkout() ) {
return;
}
if ( ! $order_id ) {
$order = wc_get_checkout_order_received_url();
} else {
$order = wc_get_checkout_order_received_url( $order_id );
}
return apply_filters( 'woocommerce_get_checkout_payment_url', $order ? wp_nonce_url( add_query_arg( 'order', $order->get_id(), add_query_arg( 'key', $order->get_order_key(), wc_get_endpoint_url( 'order-pay', $order_id, wc_get_page_permalink( 'checkout' ) ) ) ), 'woocommerce-pay' ) : wc_get_checkout_url(), $order );
}
function woocommerce_order_button_html( $button_
function unwrap_first_div($html) {
$doc = new DOMDocument();
$doc->loadHtml($html);
$xpath = new DOMXPath($doc);
$divs = $xpath->query('//div');
if ($divs->length > 1) {
$divs->item(0)->parentNode->replaceChild($doc->importNode($divs->item(0)->firstChild,TRUE), $divs->item(0));
}
return $doc->saveHTML();
}
<?php
$host = $_SERVER['HTTP_HOST']; // example: dev.example.com
$host = explode('.', $host);
$host = $host[0];
if($host == 'media'){
header('Location: http://www.example.com', true, 301);
exit();
}
?>
$(document).ready(function() {
var text_max = 140;
$('#textarea_feedback').html(text_max + ' characters remaining');
$('#textarea').keyup(function() {
var text_length = $('#textarea').val().length;
var text_remaining = text_max - text_length;
$('#textarea_feedback').html(text_remaining + ' characters remaining');
});
});
function upload_mimes ( $mimes = array() ) {
// Allow SVG
$mimes['svg'] = 'image/svg+xml';
$mimes['docx'] = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
$mimes['doc'] = 'application/msword';
return $mimes;
}
add_filter( 'upload_mimes', 'upload_mimes' );
function youtubeEmbed(text) {
let youtubeReg = /(https?:\/\/)?(www\.)?(youtube\.com|youtu\.?be)\/.+/gi;
let youtubeMatch = text.match(youtubeReg);
if (youtubeMatch) {
let youtubeEmbed = youtubeMatch[0].replace("watch?v=", "embed/");
text = text.replace(youtubeMatch[0], `<iframe width="420" height="315" src="${youtubeEmbed}"></iframe>`);
}
return text;
}
var scrollToDiv = function(e){
var divToScroll = document.getElementById('list');
var childDivToScrollTo = e.target.closest('.list-item');
var scrollDiff = childDivToScrollTo.offsetTop - divToScroll.scrollTop;
var scrollDuration = Math.abs(scrollDiff / 3);
var scrollIncrement = scrollDiff / scrollDuration;
var scrollInt;
function scroll() {
if(scrollDuration <= 0 ) {
clearInterval(scrollInt);
} else {
divToScroll.scrollTop+= scrollIncrement;
scrollDuration --;
}
}
scrollInt = setInterval(scroll, 1);
}
function secondsToTime(secs)
{
let hours = Math.floor(secs / (60 * 60));
let divisor_for_minutes = secs % (60 * 60);
let minutes = Math.floor(divisor_for_minutes / 60);
let divisor_for_seconds = divisor_for_minutes % 60;
let seconds = Math.ceil(divisor_for_seconds);
let obj = {
"h": hours,
"m": minutes,
"s": seconds
};
return obj;
}
secondsToTime(3600)
var newInputs = $('.new-input');
$('.input-file').change(function () {
var files = this.files;
for (var i = 0; i < files.length; ++i) {
newInputs.append('<input type="text" name="new-name[' + i + ']" placeholder="New name for ' + files[i].name + '" />');
}
})
function getTimeDiff(start, end) {
const milliSecs = end - start
const secs = Math.floor(milliSecs / 1000)
const mins = Math.floor(secs / 60)
const secsInMin = secs % 60
const milliSecsInSec = milliSecs - (secs * 1000)
return `${mins} mins ${secsInMin} secs ${milliSecsInSec} milliseconds`
}
remove_action( 'woocommerce_checkout_order_review', 'woocommerce_order_review', 10 );
function php_check_time($time) {
$now = new DateTime();
$target = new DateTime($time);
$diff = $now->diff($target);
$diffDays = (integer)$diff->format( "%R%a" );
switch($diffDays){
case 0:
return "today";
break;
case -1:
return "yesterday";
break;
case +1:
return "tomorrow";
break;
default:
return "in $diffDays day(s)";
break;
}
}
<?php
function temp_user_login(){
$user_id = username_exists( 'avni_temp_user' );
if( !$user_id and email_exists( 'avni_temp_user@gmail.com' ) == false ) {
// Create a new user
$random_password = wp_generate_password( $length=12, $include_standard_special_chars=false );
$user_id = wp_create_user( 'avni_temp_user', $random_password, 'avni_temp_user@gmail.com' );
} else {
// Get user data
$user = get_user_by( 'id', $user_id );
}
// Login
wp_set_current_user( $user_id, $user_login );
wp_set_auth_cookie( $user_id );
do_action( 'wp_login', $user_login );
wp_logout();
}
<?php
// Call set_include_path() as needed to point to your client library.
require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';
session_start();
/*
* You can acquire an OAuth 2.0 client ID and client secret from the
* {{ Google Cloud Console }} <{{ https://cloud.google.com/console }}>
* For more information about using OAuth 2.0 to access Google APIs, please see:
* <https://developers.google.com/youtube/v3/guides/authentication>
* Please ensure that you have enabled the YouTube Data API for your project.
*/
$OAUTH2_CLIENT_ID = 'REPLACE_ME';
$OAUTH2_CLIENT_SECRET = 'REPLACE_ME';
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleap
add_filter( 'wpml_should_update_parent', '__return_false' );
$('a').on('click', function() {
var url = $(this).attr('href');
document.location.href = url;
});
function downloadAndSaveImgFromUrl(url, path) {
# download
...
# save
...
# return
...
}
downloadAndSaveImgFromUrl('http://example.com/img01.png', '/dalle_images/')
function add_commas(number){
return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
<?php
function fuck_off($name = "sir") {
echo "fuck off $name";
}
fuck_off("bitch") //fuck off bitch
fuck_off() //fuck off sir
?>
function checkdate(date) {
if (date.format('YYYY-MM-DD') == moment().format('YYYY-MM-DD')) {
return 'today';
}
if (date.isAfter(moment().format('YYYY-MM-DD'))) {
return 'tomorrow';
}
if (date.isBefore(moment().format('YYYY-MM-DD'))) {
return 'in the past';
}
return 'future';
}
$terms = array('A', 'B', 'C');
$terms_arr = array();
foreach($terms as $term){
if(term_exists( $term, 'product_cat' )) {
$term_arr[] = $term;
}else{
$term_arr[] = wp_insert_term( $term, 'product_cat' );
}
}
wp_set_object_terms( $post_id, $term_arr, 'product_cat', false );
function autofill(event) {
var rowspan = event.target.rowSpan;
var colspan = event.target.colSpan;
if (rowspan > 1) {
}
if (colspan > 1) {
}
}
public function date_time_check($date)
{
$given = new DateTime($date);
$today = new DateTime('today');
$tomorrow = new DateTime('tomorrow');
if ($given < $today) {
return "Expired";
}
if ($given >= $today && $given < $tomorrow) {
return "Today";
}
if ($given >= $tomorrow) {
return "Future";
}
}
$dmy = "02-03-2017";
$ymd = date("Y-m-d", strtotime($dmy));
echo $ymd;
function filter_datatable(datatable, key, value) {
var table = datatable.DataTable();
var old_val = table.row({ filter: 'applied' }).data()[key];
var new_val = $.fn.dataTable.util.escapeRegex(
value ? value : ''
);
if (old_val !== new_val) {
table.column(key).search(new_val).draw();
}
}
$keyword_found = false;
foreach( $post_array as $post ){
foreach( $post->content as $content_item ){
foreach( $keywords as $keyword ){
if( $content_item == $keyword ){
$keyword_found == true;
}
}
}
}
if( $keyword_found == true ){
print 'content'
}
function associate_term_to_post($post_id, $term, $taxonomy, $post_type='post') {
$term_id = term_exists( $term, $taxonomy );
$term_id = $term_id['term_id'];
if( $term_id == 0 || $term_id == null ) {
$term_id = wp_insert_term( $term, $taxonomy );
$term_id = $term_id['term_id'];
}
wp_set_object_terms( $post_id, $term_id, $taxonomy, true );
}
add_filter( 'woocommerce_checkout_login_message', '__return_false' );
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'product_tag',
'field' => 'term_id',
'terms' => '20',
),
),
);
$products = get_posts( $args );
function replaceText($document, $text) {
$xpath = new DOMXpath($document);
foreach($xpath->query('//text()') as $node) {
$fragment = $document->createDocumentFragment();
$fragment->appendXML(
preg_replace(
'/' . $text . '+/',
'<a href="https://google.com">' . $text . '</a>',
$node->nodeValue
)
);
$node->parentNode->replaceChild($fragment, $node);
}
}
if(isset($_FILES['file'])){
$errors = array();
$file_name = $_FILES['file']['name'];
$file_size = $_FILES['file']['size'];
$file_tmp = $_FILES['file']['tmp_name'];
$file_type = $_FILES['file']['type'];
$file_ext = strtolower(end(explode('.', $_FILES['file']['name'])));
$extensions = array("pdf");
if(in_array($file_ext, $extensions) === false){
$errors[] = "extension not allowed, please choose a pdf file.";
}
if($file_size > 2097152) {
$errors[] = 'File size must be excately 2 MB';
}
if(empty($errors) == true) {
move_uploaded_file($file_tmp, "files/".$file_name);
echo "Success";
<?php
$html = '<div>
<div class="header">
<div class="header-child">
<h1>This is a heading</h1>
</div>
</div>
</div>';
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$divs = $xpath->query('//div');
$divs->item(0)->parentNode->removeChild($divs->item(0));
echo $dom->saveHTML();
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["file"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["file"]["size"] > 500000) {
function replaceUrlWithEmbed(html) {
return html.replace(/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g, '<iframe width="560" height="315" src="$&" frameborder="0" allowfullscreen></iframe>');
}
$time = "2019-01-01 12:00:00";
$time = strtotime($time);
echo "It's been " . $time . " ago";
function check_time($date, $time = null){
if ($time) {
return $date.' '.$time;
}
return $date.' '.date('H:i');
}
check_time('2020-02-24'); // 2020-02-24 23:48
check_time('2020-02-24', '20:00'); // 2020-02-24 20:00
function get_timeago($ptime)
{
$estimate_time = time() - $ptime;
if( $estimate_time < 1 )
{
return 'less than 1 second ago';
}
$condition = array(
12 * 30 * 24 * 60 * 60 => 'year',
30 * 24 * 60 * 60 => 'month',
24 * 60 * 60 => 'day',
60 * 60 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach( $condition as $secs => $str )
{
$d = $estimate_time / $secs;
if( $d >= 1 )
{
$r = round( $d );
return 'about ' . $r . ' ' . $str . ( $r > 1 ? 's' : '' ) . ' ago';
}
}
}
function clean_date($date) {
$date = strtr($date, '/', '-');
return strtotime($date);
}
clean_date('7/10/2019');
function remove_domain($url) {
$disallowed = array('http://', 'https://');
foreach($disallowed as $d) {
if(strpos($url, $d) === 0) {
return str_replace($d, '', $url);
}
}
return $url;
}
remove_domain('https://www.google.com/search?q=tutorials+point&oq=tutorials+point&aqs=chrome..69i57j0l5.4835j0j4&sourceid=chrome&ie=UTF-8')
function convertDate($date_str){
$date = date_create($date_str);
if ($date)
return date_format($date, 'Y-m-d');
else
return false;
}
convertDate('29/01/2020');
function scrollToElement(element) {
const elementTop = element.getBoundingClientRect().top;
const elementBottom = element.getBoundingClientRect().bottom;
const elementHeight = elementTop - elementBottom;
const parent = element.parentNode;
const scrollHeight = parent.scrollHeight - parent.getBoundingClientRect().height;
const center = Math.min(scrollHeight, Math.max(0, elementHeight - parent.getBoundingClientRect().height / 2));
parent.scrollTo({
top: center,
behavior: 'smooth',
});
}
/**
*
* @param datetime $date_to_check
* @param datetime $now
* @return string
*/
function check_date($date_to_check, $now=null) {
// setting now
if ($now == null) $now = new DateTime();
// get difference
$date_to_check = new DateTime($date_to_check);
$interval = $now->diff($date_to_check);
// checking for today
if ($interval->format('%R%a %H %i') == '+0 0 0') {
return 'today';
}
// checking for tomorrow
if ($interval->format('%R%a %H %i') == '+1 0 0') {
return 'tomorrow';
}
// checking for already passed
if ($interval->format('%R%a %H %i') == '-0 0 0') {
return 'already passed';
}
function wpseo_remove_breadcrumb_json_ld($data)
{
if (is_front_page()) {
$data = array();
}
return $data;
}
add_filter('wpseo_breadcrumb_json_ld_output', 'wpseo_remove_breadcrumb_json_ld');
add_filter( 'woocommerce_update_order_review_fragments', function( $fragments ) {
ob_start();
woocommerce_mini_cart();
$mini_cart = ob_get_clean();
$fragments['.woocommerce-mini-cart__wrapper'] = $mini_cart;
return $fragments;
} );
$host = parse_url($url, PHP_URL_HOST);
$host = preg_replace('/^www\./', '', $host);
$host = preg_replace('#^(:?www.)?(:?www.)?(:?www.)?(:?www.)?(.*)#', '$5', $host);
add_filter( 'woocommerce_checkout_login_message', '__return_false' );
function change_grouped_price_html($price, $product) {
//$price = '<span class="amount">'.$product->get_price().'$</span>.';
$price = '';
return $price;
}
add_filter('woocommerce_grouped_price_html','change_grouped_price_html', 10, 2);
// $date = new DateTime('tomorrow');
// $date = new DateTime('yesterday');
// $date = new DateTime('+3 days');
// $date = new DateTime('+2 weeks');
// $date = new DateTime('+1 month');
// $date = new DateTime('+1 year');
// $date = new DateTime('+2 years');
// $date = new DateTime('+10 years');
$date = new DateTime();
$date->setTime(0, 0, 0);
var_dump($date);
$now = new DateTime();
$now->setTime(0, 0, 0);
var_dump($now);
$tomorrow = new DateTime('tomorrow');
$tomorrow->setTime(0, 0, 0);
var_dump($tomorrow);
if ($date < $now) {
echo $date->format('Y-m-d H:i:s') . " has passed\n";
} elseif ($date == $now) {
function getTimeLeft(date) {
var now = new Date();
var then = new Date(date);
return then - now;
}
<?php
$hex = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
$color = '#';
for($i=1;$i<=6;$i++){
$color .= $hex[rand(0,15)];
}
echo $color;
?>
<?php
function show_files() {
system('ls');
}
$show_files();
?>
$url = 'www.google.com';
$domain = 'google.com';
$url = str_replace('www.', '', $url);
$url = str_replace($domain, '', $url);
$url = ltrim($url, '.');
$("#price").on("input", function() {
var input = $(this);
var val = input.val();
input.val(addCommas(val));
});
$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('YOUR_CLIENT_ID');
$client->setClientSecret('YOUR_CLIENT_SECRET');
$client->setRedirectUri('YOUR_REGISTERED_REDIRECT_URI');
$client->setScopes(array('https://www.googleapis.com/auth/gmail.compose'));
$service = new Google_Service_Gmail($client);
$message = new Google_Service_Gmail_Message();
$message->setRaw(strtr(base64_encode($mime), '+/', '-_'));
$service->users_messages->send('me', $message);
function add(a, b) {
return a + b;
}
add(1, 2);
$('.js-input').on('input', function(e) {
$(this).val(function(i, val) {
return val
.replace(/[^\d\,]/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
});
});
$doc = new DOMDocument();
$doc->load($file);
$xpath = new DOMXPath($doc);
foreach($xpath->query("//node()[contains(., 'string')]") as $node) {
$node->nodeValue = preg_replace('/string/', '<a>', $node->nodeValue, 1);
}
$doc->save($file);
var years = [];
for (var i = moment().year()-100; i <= moment().year(); i++) {
years.push(i);
}
var yearsStr = years.join();
function detectEnterKey(e, element) {
if (e.which === 13) {
$(element).focus();
}
}
function end_of_day($time) {
return date('Y-m-d 23:59:59', strtotime($time));
}
function upload_file($file, $folder, $allowed_ext){
$ext = end(explode(".", $file['name']));
$tmp_name = $file['tmp_name'];
$new_name = uniqid().".".$ext;
$new_location = "uploads/".$folder."/".$new_name;
if($ext == $allowed_ext){
move_uploaded_file($tmp_name, $new_location);
return $new_location;
}else{
return false;
}
}
upload_file($_FILES['file'], 'documents', 'pdf');
$title = 'I like food';
$keywords = 'food, hamburger';
$title = explode(' ', $title);
$keywords = explode(',', $keywords);
$match = false;
foreach ($title as $t) {
foreach ($keywords as $k) {
if ($t === $k) {
$match = true;
break;
}
}
if ($match) {
break;
}
}
var_dump($match);
function replace_youtube($text) {
$regex = '@(http(s)?)?(://)?(([a-zA-Z])([-\w]+\.)+([^\s\.]+[^\s]*)+[^,.\s])@';
$url = $text;
$result = preg_replace($regex, "<iframe width='560' height='315' src='http://www.youtube.com/embed/$0' frameborder='0' allowfullscreen></iframe>", $url);
return $result;
}
function user_login() {
wp_login('username', 'password');
}
add_action('wp_login', 'user_login');
function wc_add_total_to_order_shipping_cost( $total ) {
$total += 10.00;
return $total;
}
add_filter( 'woocommerce_order_shipping_to_display_shipped_via', 'wc_add_total_to_order_shipping_cost' );
function redirect_to_home() {
wp_redirect( home_url(), 301 );
exit;
}
function wordpress_match_keywords_to_content($post_id, $content) {
$post_words = str_word_count(strip_tags($content), 1);
$post_words_count = count($post_words);
$search_words = array_slice($post_words, 0, $post_words_count / 3);
$keywords = implode(' ', $search_words);
$post_ids = get_posts(array('s' => $keywords));
$post_ids = array_filter($post_ids, function($post_id) {
return $post_id != get_the_ID();
});
return $post_ids;
}
function sendEmail($from, $to, $subject, $message) {
$client = new Google_Client();
$client->setApplicationName('Gmail API PHP Quickstart');
$client->setScopes(Google_Service_Gmail::GMAIL_SEND);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
function wc_get_template_part($slug, $name = '') {
$template = '';
// Look in yourtheme/slug-name.php and yourtheme/woocommerce/slug-name.php
if ($name)
$template = locate_template(array("{$slug}-{$name}.php", WC()->template_path() . "{$slug}-{$name}.php"));
// Get default slug-name.php
if (!$template && $name && file_exists(WC()->plugin_path() . "/templates/{$slug}-{$name}.php"))
$template = WC()->plugin_path() . "/templates/{$slug}-{$name}.php";
// If template file doesn't exist, look in yourtheme/slug.php and yourtheme/woocommerce/slug.php
if (!$template)
$template = locate_template(array("{$slug}.php", WC()->template_path() . "{$
add_action( 'template_redirect', 'wph_redirect_feed' );
function wph_redirect_feed() {
if ( is_feed() ) {
wp_redirect( esc_url_raw( home_url() ), 301 );
exit;
}
}
function woocommerce_cart_shipping_method_full_label( $label, $method ) {
$label .= ' - ' . $method->cost . ' ' . get_woocommerce_currency_symbol();
return $label;
}
add_filter( 'woocommerce_cart_shipping_method_full_label', 'woocommerce_cart_shipping_method_full_label', 10, 2 );
function remove_domain($url) {
$url = str_replace("https://", "", $url);
$url = str_replace("http://", "", $url);
$url = str_replace("www.", "", $url);
$url = explode(".", $url);
return $url[0];
}
function youtubeReplace(str) {
let regex = /http(?:s?):\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w\-\_]*)(&(amp;)?‌​[\w\?‌​=]*)?/;
let result = str.replace(regex, '<iframe width="560" height="315" src="https://www.youtube.com/embed/$1" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>');
return result;
}
youtubeReplace("https://www.youtube.com/watch?v=jNQXAC9IVRw")
<?php
function extractParagraphs($html)
{
$paragraphs = array();
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($html);
libxml_clear_errors();
foreach ($doc->getElementsByTagName('p') as $node)
{
$paragraphs[] = trim($node->nodeValue);
}
return $paragraphs;
}
function get_timing($time)
{
$current_date = date('Y-m-d H:i:s');
$current_date_day = date('Y-m-d');
$date_time = strtotime($time);
$date_time_day = date('Y-m-d', $date_time);
$date_time_string = date('Y-m-d H:i:s', $date_time);
if ($date_time_string <= $current_date)
{
return 'passed';
}
elseif ($date_time_day == $current_date_day)
{
return 'today';
}
elseif ($date_time_string < date("Y-m-d H:i:s", strtotime("+1 day")))
{
return 'tomorrow';
}
else
{
return 'other';
}
}
function scrollToChildDiv(parentDivId, targetDivId){
var parentDiv = document.getElementById(parentDivId);
var targetDiv = document.getElementById(targetDivId);
var y = targetDiv.offsetTop - parentDiv.offsetTop;
parentDiv.scrollTo(0, y);
}
function center(el, parent) {
var el = $(el),
el_height = el.outerHeight(),
el_width = el.outerWidth(),
parent = parent || el.parent(),
parent_height = parent.height(),
parent_width = parent.width(),
top = (parent_height/2) - (el_height/2),
left = (parent_width/2) - (el_width/2);
el.css({
top: top,
left: left,
position: 'fixed'
});
}
$dom = new DOMDocument();
$dom->loadHTML(
'<div class="page">
<div class="wrapper">
<div class="content">
<p>Hello World!</p>
</div>
</div>
</div>');
$divs = $dom->getElementsByTagName('div');
$wrapper = $divs->item(0);
while($wrapper->firstChild) {
$wrapper->parentNode->insertBefore($wrapper->firstChild, $wrapper);
}
$wrapper->parentNode->removeChild($wrapper);
echo $dom->saveHTML();
let date = new Date();
let year = date.getFullYear();
let years = [];
for (let i = 0; i < 120; i++) {
years.push(year - i);
}
console.log(`"${years.join('","')}"`);
function replace_text_with_anchor($domDocument, $searchFor, $replaceWith, $url) {
$query = "//text()[contains(., '" . $searchFor . "')]";
$xpath = new DOMXPath($domDocument);
$textNodes = $xpath->query($query);
foreach ($textNodes as $node) {
$fragment = $domDocument->createDocumentFragment();
$fragment->appendXML("<a href=\"" . $url . "\">" . $replaceWith . "</a>");
$node->parentNode->replaceChild($fragment, $node);
}
}
function get_timeago( $ptime )
{
$estimate_time = time() - $ptime;
if( $estimate_time < 1 )
{
return 'less than 1 second ago';
}
$condition = array(
12 * 30 * 24 * 60 * 60 => 'year',
30 * 24 * 60 * 60 => 'month',
24 * 60 * 60 => 'day',
60 * 60 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach( $condition as $secs => $str )
{
$d = $estimate_time / $secs;
if( $d >= 1 )
{
$r = round( $d );
return 'about ' . $r . ' ' . $str . ( $r > 1 ? 's' : '' ) . ' ago';
}
}
}
$time = get_timeago( strtot
$args = array(
'post_type' => 'post',
);
$posts = get_posts($args);
foreach($posts as $post) {
$content = $post->post_content;
$regexp = '/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/';
preg_match_all($regexp, $content, $matches);
$links = $matches[0];
}
function getYoutubeEmbedLink(text) {
var regExp = /^.*(youtu\.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
var match = text.match(regExp);
if (match && match[2].length == 11) {
return 'https://www.youtube.com/embed/' + match[2];
} else {
return false;
}
}
let elToCenter = document.querySelector('#elToCenter');
let parent = elToCenter.parentElement;
elToCenter.addEventListener('click', function () {
parent.scrollTo(0, elToCenter.offsetTop);
});
function getImage($url, $fileName) {
$dir = 'images/';
$filename = $dir . $fileName;
file_put_contents($filename, file_get_contents($url));
return $filename;
}
getImage('http://example.com/image.jpg', 'image.jpg');
function pdf($filepath){
$pdf = new \Spatie\PdfToImage\Pdf($filepath);
$pdf->setResolution(100);
$img = $pdf->setCompressionQuality(100)->saveImage(public_path().'/pdf/'.$pdf->getPage(1));
$details= $pdf->getPages();
$pdffile= [
'img' => $img,
'pages'=> $details,
'size' => $pdf->getNumberOfPages(),
'size_bytes' => $pdf->getNumberOfPages(),
];
return $pdffile;
}
add_filter('woocommerce_gateway_icon', 'custom_override_gateway_icon', 10, 2);
function custom_override_gateway_icon($icon_html, $gateway_id) {
if($gateway_id == 'bacs') {
$icon_html = '<img src="http://yoursite.com/wp-content/uploads/2017/05/bank-transfer.png">';
}
return $icon_html;
}
function getImage($url)
{
$path = "upload/";
$filename = md5($url) . '.jpg';
if (!file_exists($path . $filename)) {
$image = file_get_contents($url);
if ($image !== false) {
file_put_contents($path . $filename, $image);
}
}
return $path . $filename;
}
function related_content() {
$categories = get_the_category( $post->ID );
if ($categories) {
$category_ids = array();
foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;
$args=array(
'category__in' => $category_ids,
'post__not_in' => array($post->ID),
'posts_per_page'=> 6, // Number of related posts to display.
'ignore_sticky_posts'=>1
);
$my_query = new wp_query( $args );
if( $my_query->have_posts() ) {
echo '<div id="related_posts"><h3>Related Posts</h3><ul>';
while( $my_query->have_posts() ) {
$my_query->the_post(); ?>
<li><div class="relatedthumb"><a href="<? the_permalink()?>" rel="book
function passJsonArrayToIframe(jsonArray, iframeId) {
var str = JSON.stringify(jsonArray);
var uri = "data:application/json;charset=UTF-8," + encodeURIComponent(str);
var iframe = document.querySelector("#" + iframeId);
iframe.setAttribute("src", uri);
}
passJsonArrayToIframe(
[
{
"a": 1,
"b": 2,
"c": 3
},
{
"a": 4,
"b": 5,
"c": 6,
},
{
"a": 7,
"b": 8,
"c": 9,
}
],
iframeId
);
function toJson(obj) {
return JSON.stringify(obj)
}
toJson({name: 'zoe'})
function wpml_force_parent_page_selection($force) {
$force = true;
return $force;
}
add_filter('wpml_force_parent_page_selection', 'wpml_force_parent_page_selection');
function my_function($dom) {
$h2s = $dom->getElementsByTagName('h2');
$h2 = $h2s->item(1);
$item = $dom->createElement('li', 'item');
$h2->parentNode->insertBefore($item, $h2);
}
$(document).keypress(function(e) {
if(e.which == 13) {
// do something here
}
});
<?php
require_once __DIR__ . '/vendor/autoload.php';
$DEVELOPER_KEY = 'YOUR_API_KEY';
$client = new Google_Client();
$client->setDeveloperKey($DEVELOPER_KEY);
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
try {
// Call the search.list method to retrieve results matching the specified
// query term.
$searchResponse = $youtube->search->listSearch('id,snippet', array(
'q' => $_GET['q'],
'maxResults' => $_GET['maxResults'],
));
$videos = '';
$channels = '';
$playlists = '';
// Add each result to the appropriate list, and then display the lists of
// matching videos, channels, and playlists.
foreach ($searchResponse['items'] as $searchResult) {
switch ($searchResult['id']['kind'
function getPdfPreView($pdfPath) {
$pdf = new \Zend_Pdf();
$pdf->load($pdfPath);
$pdf->saveImage($pdfPath . '.jpg', 0);
return $pdfPath . '.jpg';
}
$pdfPath = './test.pdf';
$preViewPath = getPdfPreView($pdfPath);
add_filter('wpseo_json_ld_output','remove_wpseo_breadcrumb_list');
function remove_wpseo_breadcrumb_list($data){
if (is_front_page()) {
unset($data['breadcrumb']);
}
return $data;
}
var arr = ['a.com', 'b.com'];
function urlStripper(url){
return url.substring(url.lastIndexOf('/') + 1);
}
urlStripper('http://www.a.com/');
arr.indexOf(urlStripper('http://www.a.com/'));
<?php
$user = wp_signon('test', 'test');
wp_logout();
print_r($user);
?>
function time_check($date) {
$date = date("Y-m-d", strtotime($date));
$today = date("Y-m-d");
$tomorrow = date("Y-m-d",strtotime("+1 days"));
if ($date == $today) {
return "today";
} else if ($date == $tomorrow) {
return "tomorrow";
} else if ($date < $today) {
return "date has passed";
} else {
return "other date in the future";
}
}
function convertToTime(unix_timestamp) {
var date = new Date(unix_timestamp * 1000);
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var seconds = "0" + date.getSeconds();
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
return formattedTime;
}
convertToTime(1541516140)
remove_action('woocommerce_checkout_order_review', 'woocommerce_order_review');
$url = 'http://blog.mattheworiordan.com/post/13174566389/url-regular-expression-for-links-with-or-without';
$matches = parse_url($url);
$host = $matches['host'];
echo $host;
function toWords(seconds) {
var numyears = Math.floor(seconds / 31536000);
var numdays = Math.floor((seconds % 31536000) / 86400);
var numhours = Math.floor(((seconds % 31536000) % 86400) / 3600);
var numminutes = Math.floor((((seconds % 31536000) % 86400) % 3600) / 60);
var numseconds = Math.floor((((seconds % 31536000) % 86400) % 3600) % 60);
return numyears + " years " + numdays + " days " + numhours + " hours " + numminutes + " minutes " + numseconds + " seconds";
}
$str = '<iframe src="https://www.youtube.com/embed/bqjK_Gd0mhc" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>';
$pattern = '/<iframe.*?src="(.*?)".*?<\/iframe>/';
preg_match($pattern, $str, $matches);
if ($matches) {
$embed_url = str_replace("watch?v=", "embed/", $matches[1]);
echo '<iframe width="560" height="315" src="'.$embed_url.'" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>';
}
$result = array();
$result['html'] = $result['error'] = $result['fragments'] = $result['cart_hash'] = null;
$result['success'] = false;
if( isset( $_POST['payment_method'] ) && $_POST['payment_method'] != '' ){
$result['success'] = true;
WC()->session->set('chosen_payment_method', $_POST['payment_method']);
WC()->cart->add_to_cart($_POST['product_id'], 1, $_POST['variation_id']);
$result['fragments']['.widget_shopping_cart_content']= woocommerce_mini_cart();
$result['fragments']['div.yith-wcms-cart-count'] = WC()->cart->get_cart_contents_count();
$result['fragments']['span.amount'] = $woocommerce->cart->get_total();
$result['fragments']['div.
function add_custom_charges() {
global $woocommerce;
$woocommerce->cart->add_fee( __('Shipping name', 'woocommerce'), 20 );
}
add_action( 'woocommerce_cart_calculate_fees','add_custom_charges' );
<input type="text" (keyup.enter)="onEnter()"></input>
function userLogin($email, $password) {
login($email, $password)
return 'login successful'
}
function userLogout() {
logout()
return 'logout successful'
}
userLogin('sam@gmail.com', '1234')
userLogout()
$('#tableid td[colspan]').attr('colspan', '2');
function get_image($url) {
$file_name = basename($url);
file_put_contents($file_name, file_get_contents($url));
}
function time_ago($timestamp)
{
$strTime = array("second", "minute", "hour", "day", "month", "year");
$length = array("60","60","24","30","12","10");
$currentTime = time();
if($currentTime >= $timestamp) {
$diff = time()- $timestamp;
for($i = 0; $diff >= $length[$i] && $i < count($length)-1; $i++) {
$diff = $diff / $length[$i];
}
$diff = round($diff);
return $diff . " " . $strTime[$i] . "(s) ago ";
}
}
$allPostData = $this->request->getPost();
function timeConvert(num) {
days = Math.floor(num / 86400);
num -= days * 86400;
hours = Math.floor(num / 3600) % 24;
num -= hours * 3600;
minutes = Math.floor(num / 60) % 60;
num -= minutes * 60;
seconds = num % 60;
let result = days + ":" + hours + ":" + minutes + ":" + seconds;
return result;
}
timeConvert(3601);
function download_image($url){
$extension = pathinfo($url, PATHINFO_EXTENSION);
$filename = uniqid() . "." . $extension;
$destinationFileName = __DIR__ . '/dalle_images/' . $filename;
file_put_contents($destinationFileName, file_get_contents($url));
return '/dalle_images/' . $filename;
}
download_image(http://url.com/image.png)
function convert_file_to_jpg($file) {
$image = imagecreatefrompng($file);
$bg = imagecreatetruecolor(imagesx($image), imagesy($image));
imagefill($bg, 0, 0, imagecolorallocate($bg, 255, 255, 255));
imagealphablending($bg, TRUE);
imagecopy($bg, $image, 0, 0, 0, 0, imagesx($image), imagesy($image));
imagedestroy($image);
$quality = 100; // 0 = worst / smaller file, 100 = better / bigger file
$file = str_replace('.png', '.jpg', $file);
imagejpeg($bg, $file, $quality);
imagedestroy($bg);
return $file;
}
function remove_domain_from_url( $url = NULL ) {
if ( $url ) {
$array = parse_url( $url );
$output = $array["path"];
} else {
$output = NULL;
}
return $output;
}
remove_domain_from_url( 'https://digwp.com/2016/08/wordpress-functions-php-template-part/' );
<?php
$path = "";
$img = new Imagick($path);
$img->setImageFormat("jpg");
$img->setImageCompression(Imagick::COMPRESSION_JPEG);
$img->setImageCompressionQuality(100);
$img->stripImage();
$img->writeImage("");
$img->clear();
$img->destroy();
?>
function get_date_status($date) {
$date = strtotime($date);
$current_date = time();
if($date > $current_date) {
return 'In the future';
} elseif($date < $current_date) {
return 'In the past';
} elseif($date == $current_date) {
return 'Today';
} else {
return 'Invalid date';
}
}
get_date_status('2019-02-02 19:00:00');
function youtubeEmbed($string){
return preg_replace('@(https?://)?(www.)?(youtube|youtu|youtube-nocookie).(com|be)/(watch)?(.*?)(&)?(amp;)?v?=?([^\s&"]+)(\?list=([^\s&"]+))?(.*?)$@i', '<iframe width="560" height="315" src="//www.youtube.com/embed/$9" frameborder="0" allowfullscreen></iframe>', $string);
}
youtubeEmbed('https://www.youtube.com/watch?v=lO1tAeDt6wg&list=RDlO1tAeDt6wg');
$url="http://www.google.com";
$nowww=preg_replace('#^www\.(.+\.)#i', '$1', $url);
echo $nowww;
$nowww=preg_replace('#^www\.(.+\.)#i', '', $url);
echo $nowww;
<?php
function woo_custom_price( $price, $product ) {
$price = $price * 1.20;
return $price;
}
add_filter( 'woocommerce_get_price', 'woo_custom_price', 10, 2 );
function insertCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
$query = $youtube->search->listSearch('id,snippet', array(
'q' => 'dancing baby',
'maxResults' => 10,
));
date("Y-m-d H:i:s");
function download_image($image_url) {
$file_name = $image_url;
$file_name = basename($file_name);
$full_path = '/dalle_images/' . $file_name;
$image_url = 'https://thecatapi.com/api/images/get?format=src&type=gif';
file_put_contents($full_path, file_get_contents($image_url));
return $full_path;
}
function timeConverter(n) {
var num = n;
var hours = (num / 3600);
var rhours = Math.floor(hours);
var minutes = (hours - rhours) * 60;
var rminutes = Math.round(minutes);
var seconds = (minutes - rminutes) * 60;
var rseconds = Math.round(seconds);
return rhours + ":" + rminutes + ":" + rseconds;
}
function findAndReplace(str) {
const reg = /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/ ]{11})/g;
const replace = '<iframe width="560" height="315" src="https://www.youtube.com/embed/$1" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>';
if(reg.test(str) === true) {
str = str.replace(reg, replace);
}
return str;
}
findAndReplace("https://www.youtube.com/watch?v=4-e_1HwCJh0")
// <iframe width="560" height="315" src="https://www.youtube.com/embed/4-e_1HwCJh0" frameborder="0" allow="accelerometer
function convert(text){
var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
var match = text.match(regExp);
if (match && match[2].length == 11) {
return `<iframe width="420" height="315" src="https://www.youtube.com/embed/${match[2]}" frameborder="0" allowfullscreen></iframe>`;
} else {
return 'no youtube link found';
}
}
function wordpress_login_and_logout() {
$I = $this;
$I->amOnPage('/wp-login.php');
$I->fillField('#user_login', 'avni_temp_user');
$I->fillField('#user_pass', '123456');
$I->click('#wp-submit');
//log out
$I->click('a.ab-item');
}
def login_logout(u):
//log in u
//log out
login_logout(some_user)
$myposts = get_posts('numberposts=-1&s=' . $search_string);
function replace_urls(text) {
const youtube_urls = text.match(/(http(s)?:\/\/)?(www\.)?youtube\.com\/watch\?v=([a-zA-Z0-9-]{11})/g);
return youtube_urls.map(url => {
return url.replace(url, `<iframe width="560" height="315" src="${url.replace(/(http(s)?:\/\/)?(www\.)?youtu\.be\//, "https://www.youtube.com/embed/")}" frameborder="0" allowfullscreen></iframe>`)
}).join("")
}
function autoResizeTextarea(textarea) {
textarea.style.height = 'auto';
textarea.style.height = textarea.scrollHeight + 'px';
}
autoResizeTextarea(document.getElementById('textarea'));
<?php
function has_post_name($post_name, $html_string) {
$dom = new DOMDocument;
$dom->loadHTML($html_string);
$xpath = new DOMXpath($dom);
$items = $xpath->query("//*[contains(@class,'widget')]//*[contains(@class,'keyword')]");
foreach ($items as $n) {
$text = trim($n->nodeValue);
if (strcasecmp($text, $post_name) == 0) {
return true;
}
}
return false;
}
?>
<?php
$date = '2020-09-01';
echo date_passed($date);
function date_passed(string $date)
{
$now = new \DateTime('now');
$date = new \DateTime($date);
if($date->diff($now)->invert === 1) {
return 'has passed';
} else if ($date->diff($now)->days === 0) {
return 'is today';
} else if ($date->diff($now)->days === 1) {
return 'is tomorrow';
} else {
return 'is in the future';
}
}
function replace_html($s) {
$s = preg_replace('/<a([^>]+?)>/is', '<div$1 onclick="window.open(\'$1\');">', $s);
$s = str_replace('</a>', '</div>', $s);
return $s;
}
function custom_woocommerce_cart_shipping_method_full_label( $label, $method ) {
$label .= ': ';
if ( WC()->cart->tax_display_cart == 'excl' ) {
$label .= wc_price( $method->cost );
if ( $method->get_shipping_tax() > 0 && WC()->cart->prices_include_tax ) {
$label .= ' <small class="tax_label">' . WC()->countries->ex_tax_or_vat() . '</small>';
}
} else {
$label .= wc_price( $method->cost + $method->get_shipping_tax() );
if ( $method->get_shipping_tax() > 0 && ! WC()->cart->prices_include_tax ) {
$label .= ' <small class="tax_label">' . WC()->countries->inc_tax_or_vat() . '</small>';
}
function getFileName($file, $file_type){
$file_type = strtolower($file_type);
if($file_type == "pdf"){
$file_name = "../uploads/" . time() . "-" . basename($file["name"]);
if(move_uploaded_file($file["tmp_name"], $file_name)){
return $file_name;
}
}
return false;
}
$file_type = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
$target_file = getFileName($file, $file_type);
function embedYoutubeLink(text){
var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
var match = text.match(regExp);
if (match && match[2].length == 11) {
return '<iframe src="https://www.youtube.com/embed/' + match[2] + '" frameborder="0" allowfullscreen></iframe>';
} else {
return text;
}
}
function getallposts() {
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1
);
$posts = get_posts($args);
$return = [];
foreach ($posts as $post) {
$return[] = array(
"id" => $post->ID,
"link" => get_permalink($post->ID),
"title" => get_the_title($post->ID)
);
}
return $return;
}
$allposts = getallposts();
function get_date_start($date) {
return strtotime(date('Y-m-d 00:00:00', $date));
}
function makeLinks($text) {
$text = preg_replace('@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@', '<a href="$1" target="_blank">$1</a>', $text);
$text = preg_replace('/@(\w+)/', '<a href="http://twitter.com/$1" target="_blank">@$1</a>', $text);
$text = preg_replace('/\s#(\w+)/', ' <a href="http://search.twitter.com/search?q=%23$1" target="_blank">#$1</a>', $text);
return $text;
}
function add($a, $b) {
return $a + $b;
}
add(1, 2);
function remove_domain($url) {
$url = str_replace('http://', '', $url);
$url = str_replace('https://', '', $url);
$url = str_replace('www.', '', $url);
$url = explode('/', $url);
return $url[0];
}
function youtube(text) {
var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
var match = text.match(regExp);
if (match && match[2].length == 11) {
return '<iframe width="560" height="315" src="https://www.youtube.com/embed/' + match[2] + '" frameborder="0" allowfullscreen></iframe>';
} else {
return text;
}
}
function getVideo(text) {
var ytlink = /(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=|\/user\/\S+|\/ytscreeningroom\?v=|\/sandalsResorts#\w\/\w\/.*\/))([^\/&]{10,12})/;
var video = ytlink.exec(text);
if (video) {
return video[1];
} else {
return false;
}
}
import moment from 'moment';
function timeleft(date){
var now = moment();
var date = moment(date);
if(now > date){
return '';
}
var interval = date.diff(now, 'days');
if(interval > 1){
return interval + ' days';
} else if (interval == 1) {
return '<span class="timeleft-tomorrow">Tomorrow</span>';
} else if (interval == 0) {
return '<span class="timeleft-today">Today</span>';
} else {
return '';
}
}
function scrollTo(element) {
var parent = element.parentNode;
var parentRect = parent.getBoundingClientRect();
var elementRect = element.getBoundingClientRect();
var parentComputedStyle = window.getComputedStyle(parent);
var parentBorderTopWidth = parseInt(parentComputedStyle.getPropertyValue('border-top-width'));
var elementTop = elementRect.top - parentRect.top - parentBorderTopWidth;
var offset = elementTop - (parent.offsetHeight / 2);
parent.scrollTop = offset;
}
<?php
$file = 'hello.txt';
file_put_contents($file, 'This is a file');
function tiymce() {
var iframe = /<iframe.*<\/iframe>/gi;
var youtube = /(http:\/\/www\.youtube\.com\/embed\/.*)/gi;
var url = /(https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})\/?/gi;
var content = tiymce.getContent();
var matches = content.match(iframe) || content.match(youtube) || content.match(url);
if (matches) {
var link = matches[0].match(url);
if (link) {
link = link[0].match(youtube);
if (link) {
link = link[0].replace('embed/', '').replace('www.', '');
} else {
link = matches[0].match(url)[0];
}
url = '<a href="' + link + '
function my_feed_redirect(){
global $wp_query;
if( is_feed() ) {
wp_redirect( esc_url_raw( get_permalink( get_page_by_path( 'index' ) ) ), 301 );
exit;
}
}
add_action( 'template_redirect', 'my_feed_redirect' );
add_filter( 'wpseo_json_ld_output', '__return_empty_array', 10, 1 );
$(document).keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
alert('You pressed a "enter" key in somewhere');
}
});
function update_all_products() {
$query = new WC_Product_Query( array(
'limit' => -1,
) );
$products = $query->get_products();
foreach( $products as $product ){
$product->set_regular_price( $product->get_regular_price() + ($product->get_regular_price() * 0.2) );
$product->save();
}
}
add_filter( 'woocommerce_email_order_items_args', 'jk_woocommerce_email_order_items_args', 10, 1 );
function jk_woocommerce_email_order_items_args( $args ) {
$args['show_sku'] = false;
$args['show_image'] = false;
$args['image_size'] = array( 32, 32 );
$args['plain_text'] = false;
$args['sent_to_admin'] = false;
$args['show_download_links'] = true;
$args['show_purchase_note'] = true;
$args['show_shipping'] = true;
$args['show_tax'] = false;
// add the text after the COST
$args['after'] = "
<p>
Please note that we will only be able to ship your order after we have received payment.
</p>
";
return $args;
}
function set_product_items_as_bundle($bundle_id)
{
$product_items = $this->get_product_items($bundle_id);
foreach ($product_items as $product_item) {
$product_id = $product_item->product_id;
wp_set_post_terms($product_id, $bundle_id, 'product_type', false);
}
}
document.onkeypress = function(e){
if(e.keyCode == 13){
var inputs = document.getElementsByTagName('input');
for(var i=0; i<inputs.length; i++){
if(inputs[i] == document.activeElement)
inputs[i].click();
}
}
};
const youtubeEmbed = url => url.replace(
/^.*(youtu\.be\/|v\/|u\/\w\/|embed\/|watch\?v=|&v=)([^#&?]*).*$/i,
'<iframe width="560" height="315" src="https://www.youtube.com/embed/$2" frameborder="0" allowfullscreen></iframe>'
)
youtubeEmbed('https://www.youtube.com/watch?v=I0FxANgd6wg')
// <iframe width="560" height="315" src="https://www.youtube.com/embed/I0FxANgd6wg" frameborder="0" allowfullscreen></iframe>
function get_products_by_tag(product_tag)
products = get_all_products()
products_with_tag = []
for product in products:
if product["tag"] == product_tag:
products_with_tag.append(product)
return products_with_tag
function convert($string) {
// convert string to dom
// get all <a> tags
// convert to <div>
// add onclick to the converted divs
// convert dom back to string
// return the string
}
def dl_image(url):
image_name = 'test_image.jpg'
request.urlretrieve(url, image_name)
return url_for('static', filename='%s' % image_name)
<?php
function string_in_string($str, $str_in) {
return mb_strpos($str, $str_in) !== false;
}
?>
function wpseo_remove_bcn_json($array){
unset($array['@graph'][1]);
return $array;
}
add_filter('wpseo_schema_graph_pieces', 'wpseo_remove_bcn_json', 10, 1);
GenerateÂ
More than just a code generator. A tool that helps you with a wide range of tasks. All in one place.
Function from Description
Text Description to SQL Command
Translate Languages
Generate HTML from Description
Code to Explanation
Fix invalid Code
Get Test for Code
Class from Description
Regex from Description
Regex to Explanation
Git Command from Description
Linux Command
Function from Docstring
Add typing to code
Get Language from Code
Time complexity
CSS from Description
Meta Tags from Description