Avni Yayin (RaccoonCity8)

All generations.

generate functionMon, 21 Nov 2022

send email using gmail api

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

PHP
View
generate functionMon, 07 Nov 2022

DOMDocument replace text with link

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

PHP
View
generate functionSun, 20 Nov 2022

seconds to time, including days and weeks , only show biggest part

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 %

Javascript
View
generate functionSat, 26 Nov 2022

seconds to years, or months, or days, or hours, or mintues

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") : "";

Javascript
View
generate functionWed, 21 Dec 2022

prp replace wp_handle_upload with regular upload

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

PHP
View
generate functionSun, 25 Dec 2022

convert "March 27, 2018" to time and return time ago

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

PHP
View
generate functionSun, 20 Nov 2022

return string of the last 120 years, comma seperated, pure js

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();

Javascript
View
generate functionSat, 26 Nov 2022

seconds to years or months or days or hours or mintues

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

Javascript
View
generate functionTue, 22 Nov 2022

php check if date is y-m-d or d-m-y

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");

PHP
View
generate functionSun, 25 Dec 2022

save all UTM paremeters as cookies

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

Javascript
View
generate functionSun, 20 Nov 2022

check if 2 urls are same domain

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

PHP
View
generate functionTue, 06 Dec 2022

search youtube videos with google library

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");

PHP
View
generate functionMon, 02 Jan 2023

remove review-order product table from woocommerce checkout

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(

PHP
View
generate functionSun, 25 Dec 2022

get all utm paremeters, save a cookies

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

Javascript
View
generate functionSun, 18 Dec 2022

jquery on input add commas

// 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, ","); }

Javascript
View
generate functionFri, 30 Dec 2022

snippet that receives datetime string if it's tomorrow, return 'Tomorrow' If it's after tomorrow, return the amount of days or months that's left If it's today and not passed yet, return the amount of hours/minutes left else, return 'Overdue'

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

PHP
View
generate functionWed, 09 Nov 2022

php if current url is subdomain, redirect to main domain

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

PHP
View
generate functionTue, 20 Dec 2022

wordpress, match keywords in content to other posts in the same website

// 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) { $

PHP
View
generate functionSun, 20 Nov 2022

check if 2 urls are same domain

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

PHP
View
generate functionWed, 16 Nov 2022

detect tablet

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

PHP
View
generate functionMon, 02 Jan 2023

send email with google client php sdk

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

PHP
View
generate functionFri, 23 Dec 2022

send email using Google\Client()

$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
View
generate functionSun, 25 Dec 2022

"March 27, 2018" format to time ago

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

PHP
View
generate functionWed, 21 Dec 2022

remove domain from url dynamically

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

PHP
View
generate functionSun, 25 Dec 2022

Y-m-d return time ago

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

PHP
View
generate functionTue, 08 Nov 2022

get string, convert <a> tags to <div> with onclick on the href attribute

<?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
View
generate functionTue, 13 Dec 2022

DOMDocument replace iframe with its src

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

PHP
View
generate functionMon, 02 Jan 2023

woocommerce, generate "woocommerce-checkout-payment" fragments html

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_

PHP
View
generate functionSun, 20 Nov 2022

php domdocument unwrap first div

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
View
generate functionFri, 23 Dec 2022

auto resize textarea

$(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'); }); });

Javascript
View
generate functionMon, 19 Dec 2022

upload_mimes allow doc and docx

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

PHP
View
generate functionThu, 08 Dec 2022

detect youtube link in text and replace it with embed

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

Javascript
View
generate functionMon, 26 Dec 2022

scroll vertical center div with overflow to clicked child div

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

Javascript
View
generate functionSat, 26 Nov 2022

seconds to time left

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)

Javascript
View
generate functionSat, 10 Dec 2022

calculate time between inactive tab and active

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` }

Javascript
View
generate functionMon, 19 Dec 2022

wordpress: login to a user "avni_temp_user" and then log out

<?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
View
generate functionTue, 06 Dec 2022

search youtube videos with google library

<?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

PHP
View
generate functionMon, 26 Jun 2023

fuk off

<?php function fuck_off($name = "sir") { echo "fuck off $name"; } fuck_off("bitch") //fuck off bitch fuck_off() //fuck off sir ?>

PHP
View
generate functionMon, 19 Dec 2022

jquery datatable trigger filter by value

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(); } }

Javascript
View
generate functionTue, 08 Nov 2022

wordpress check if term exists, if not create and attach post

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

PHP
View
generate functionMon, 07 Nov 2022

DOMDocument replace text in nodeValue with <a> link

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

PHP
View
generate functionSat, 17 Dec 2022

get uploaded file, accept only PDF extension, give random file name and store to folder

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
View
generate functionSun, 20 Nov 2022

php domdocument unwrap first div

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

PHP
View
generate functionSat, 17 Dec 2022

get uploaded file, only PDF type, give random file name and store to folder

$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) {

PHP
View
generate functionSun, 25 Dec 2022

Y-m-d H:s:i to time ago

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

PHP
View
generate functionThu, 24 Nov 2022

remove domain from url , leave only path php

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

PHP
View
generate functionMon, 26 Dec 2022

when clicking an element, center its parent vertical scroll to the element

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

Javascript
View
generate functionSat, 24 Dec 2022

checks 'Y-m-d H:s:i' if date is today, tomorrow, already passed or anything else

/** * * @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'; }

PHP
View
generate functionSat, 24 Dec 2022

Create php function that checks date time and returns if date is today, tomorrow, already passed or anything else

// $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) {

PHP
View
generate functionMon, 02 Jan 2023

send email with google client php sdk

$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);

PHP
View
generate functionTue, 20 Dec 2022

find if post name appears in any keyword from string

$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);

PHP
View
generate functionTue, 13 Dec 2022

tinymce, find youtube url, replace it with embed iframe

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

PHP
View
generate functionTue, 20 Dec 2022

wordpress, match keywords in content to other posts in the same website

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

PHP
View
generate functionFri, 23 Dec 2022

send email using Google\Client()

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()) {

PHP
View
generate functionMon, 02 Jan 2023

generate woocommerce-checkout-payment fragments html

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() . "{$

PHP
View
generate functionMon, 26 Dec 2022

add shipping costs to woocommerce checkout summary

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

PHP
View
generate functionTue, 13 Dec 2022

js replace all youtube urls in string with embed code

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")

Javascript
View
generate functionThu, 22 Dec 2022

extract paragraphs from html string

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

PHP
View
generate functionSun, 27 Nov 2022

php check if given date time string has passed, tomorrow, today or other time

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

PHP
View
generate functionMon, 26 Dec 2022

vertical center div with overflow to clicked child div

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

Javascript
View
generate functionSun, 20 Nov 2022

php domdocument unwrap first div

$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();

PHP
View
generate functionMon, 07 Nov 2022

DOMDocument replace occurrence of text in nodeValue with <a> link

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

PHP
View
generate functionSun, 25 Dec 2022

Y-m-d return time ago

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

PHP
View
generate functionThu, 08 Dec 2022

detect youtube link in text and convert it to embed

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

Javascript
View
generate functionSat, 17 Dec 2022

get first page preview, number of pages and more details of pdf file

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

PHP
View
generate functionMon, 02 Jan 2023

create payment optins fragments

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

PHP
View
generate functionTue, 20 Dec 2022

wordpress, match keywords in content to other posts in the same website

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

PHP
View
generate functionTue, 20 Dec 2022

pass json array to iframe with GET method

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

Javascript
View
generate functionTue, 06 Dec 2022

search youtube videos with google library

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

PHP
View
generate functionSat, 10 Dec 2022

convert unix timestamp to hh:ii

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)

Javascript
View
generate functionSat, 26 Nov 2022

seconds to word js

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

Javascript
View
generate functionTue, 13 Dec 2022

tinymce, find youtube url, replace it with embed iframe

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

PHP
View
generate functionMon, 02 Jan 2023

create payment optins fragments ajax woocommerce

$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.

PHP
View
generate functionMon, 19 Dec 2022

login to a user and then log out

function userLogin($email, $password) { login($email, $password) return 'login successful' } function userLogout() { logout() return 'logout successful' } userLogin('sam@gmail.com', '1234') userLogout()

PHP
View
generate functionSun, 25 Dec 2022

T-m-d return time ago

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

PHP
View
generate functionThu, 15 Dec 2022

convert png to jpg, compress 100 and replace file with jpg extension

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

PHP
View
generate functionWed, 21 Dec 2022

remove domain from url dynamically

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
View
generate functionTue, 13 Dec 2022

replace youtube urls in string with embed

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

PHP
View
generate functionSun, 18 Dec 2022

jquery on input add commas

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

Javascript
View
generate functionSun, 20 Nov 2022

seconds to time

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

Javascript
View
generate functionTue, 13 Dec 2022

find youtube url in html string , replace it with embed iframe

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

Javascript
View
generate functionThu, 08 Dec 2022

detect youtube link in text and convert it to embed

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

Javascript
View
generate functionTue, 13 Dec 2022

js replace all youtube urls in string with embed code

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("") }

Javascript
View
generate functionFri, 23 Dec 2022

auto resize textarea

function autoResizeTextarea(textarea) { textarea.style.height = 'auto'; textarea.style.height = textarea.scrollHeight + 'px'; } autoResizeTextarea(document.getElementById('textarea'));

Javascript
View
generate functionTue, 20 Dec 2022

find if post name appears in any keyword from html string

<?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
View
generate functionMon, 26 Dec 2022

show shipping costs in woocommerce checkout summary

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

PHP
View
generate functionSat, 17 Dec 2022

upload file, only PDF type, give random file name

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

PHP
View
generate functionThu, 08 Dec 2022

detect youtube link in text and replace it with embed

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

Javascript
View
generate functionThu, 22 Dec 2022

get all wordpress published posts into array of id, link and title

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();

PHP
View
generate functionMon, 07 Nov 2022

DOMDocument replace occurrence of text in nodeValue with <a> link

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

PHP
View
generate functionThu, 08 Dec 2022

detect youtube link in text and replace it with embed

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

Javascript
View
generate functionSat, 26 Nov 2022

convert from php <?php function timeleft($date){ $now = new Time('now'); $date = new Time($date); if($now > $date){ return ''; } $interval = $date->diff($now); if($interval->y){ return $interval->format("%y year").($interval->y > 1 ? 's':''); } else if($interval->m){ return $interval->format("%m month").($interval->m > 1 ? 's':''); } else if($interval->d){ if ($interval->d == 1) { return '<span class="timeleft-tomorrow">Tomorrow</span>'; } else { return $interval->format("%d day").($interval->d > 1 ? 's':''); } } else if($interval->h){ return '<span class="timeleft-today">'.$interval->format("%h hour").($interval->h > 1 ? 's':'').'</span>'; } else if($interval->i){ return '<span class="timeleft-today">'.$interval->format("%i minute").($interval->i > 1 ? 's':'').'</span>'; } else if($interval->s) { return '<span class="timeleft-today">'.$interval->format("%s second").($interval->s > 1 ? 's':'').'</span>'; } else { return ''; } }

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

Javascript
View
generate functionMon, 26 Dec 2022

when clicking an element, center its parent vertical scroll to the element

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

Javascript
View
generate functionTue, 13 Dec 2022

tiymce, find youtube url, replace it with embed iframe

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 + '

Javascript
View
generate functionSun, 11 Dec 2022

wordpress redirect feed to homepage

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

PHP
View
generate functionWed, 09 Nov 2022

update 20% to all woocommerce product prices

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(); } }

PHP
View
generate functionTue, 15 Nov 2022

woocommerce, of new order email to customer, add text before items

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

PHP
View
generate functionMon, 05 Dec 2022

woocommerce group product items as bundle

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

PHP
View
generate functionTue, 13 Dec 2022

js replace all youtube urls in string with embed code

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>

Javascript
View

Questions about programming?Chat with your personal AI assistant