CHEAT SHEET

by Léandre Nargeot

Version

index

html

meta viewport

<meta name="viewport" content="width=device-width, initial-scale=1.0">

barre title smartphone

<meta name="theme-color"  content="#ffffff">

footer toujours en bas

body
  .wrapper
    header.header
    main.site-main
    footer.footer
.wrapper
  min-height: 100vh
  display: flex
  flex-direction: column
  
.site-main
  display: flex
  flex: 1
  flex-direction: column
  
.footer
  background-color: grey

souris scroll html/css

<div class="project__scroll">
	<div class="project__scrollLine"></div>
	<div class="project__scrollText"></div>
</div>
.project__scroll {
  z-index: 1;
  position: absolute;
  left: 50%;
  top: 90vh;
  -webkit-transform: translateX(-50%);
  transform: translateX(-50%);
  border: solid 2px white;
  width: 20px;
  height: 35px;
  border-radius: 9px;
  }
.project__scrollLine {
  z-index: 1;
  width: 7px;
  height: 7px;
  border-radius: 50%;
  background: white;
  left: 50%;
  position: relative;
  top: 5px;
  transform: translateX(-50%);
  animation: scroll 2s infinite;
}
@keyframes scroll{
  0% {top: 5px;}
  40% {top: 10px;}
  100% {top: 5px;}
}

souris scroll 2 pug/sass

.hero--scroll
	.hero--stroke
.hero
	&--scroll
		bottom: 0
		right: 3.472vw
		z-index: 5
		width: 1px
		height: 4.167vw
		overflow: hidden
		background: #fff
		position: absolute
	&--stroke
		top: 0
		left: 0
		width: 1px
		height: 100%
		background: red
		position: absolute
		transform: translate(0%,  -100%)
		animation-name: scroll
		animation-duration: 2s
		animation-iteration-count: infinite

@keyframes scroll
	0%
		transform: translate(0%,  -100%)
	100%
		transform: translate(0%,  100%)

video #t= start at

<video>
    <source src="splash.mp4#t=10,20" type="video/mp4">
</video>

iframe 1

<div id="outdiv">
	<iframe src="http://www.lien.com" scrolling="no" width="1280px" height="1200px" id="iniframe"></iframe>
</div> 
#outdiv { 
	height: 205px; 
	overflow: hidden; 
	position: relative; 
	width: 915px; 
} 
#iniframe { 
	height: 1200px; 
	left: -180px; 
	position: absolute; 
	top: -240px; 
	width: 1280px; 
}

iframe 2

<iframe  
src="http://www.lien.com"  
id="iniframe"  
width="100%"  
height="100%"  
scrolling="auto"  
frameborder="0"  >  
</iframe>
html,body{  
	width:100%;  
	height:100%;  
	margin:0px;  
	padding:0px;  
}

Accordéon

<ul class="accordion" data-speed="150"> 
	<li class="accordion-item active"> 
		<h3 class="accordion-title">...</h3> 
		<div class="accordion-content">...</div> 
	</li> 
	<li class="accordion-item"> 
		<h3 class="accordion-title">...</h3> 
		<div class="accordion-content">...</div> 
	</li> 
</ul>
$('.accordion').each(function(e) {
	var accordion = $(this);
	var toggleSpeed = accordion.attr('data-speed') || 100;

	function open(item, speed) {
		accordion.find('.accordion-item').not(item).removeClass('active')
			.find('.accordion-content').slideUp(speed);
		item.addClass('active')
			.find('.accordion-content').slideDown(speed);
	}

	open(accordion.find('.active:first'), 0);

	accordion.on('click', '.accordion-title', function(ev) {
		ev.preventDefault();
		open($(this).closest('.accordion-item'), toggleSpeed);
	});
});

.htacces

Modifier l’index of /
  1. A la racine créer
HeaderName /style/HEADER.html
ReadmeName /style/README.html
IndexIgnore /style
Mettre le site en HTTPS
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] 

reCaptcha

<script src="https://www.google.com/recaptcha/api.js?render=SITEKEY"></script>
<script src="https://www.google.com/recaptcha/api.js?render=SITEKEY"></script>  
<script>  
	grecaptcha.ready(function()  {  
		grecaptcha.execute('SITEKEY',  {action:'homepage'}).then(function(token)  {  
			// pass the token to the backend script for verification  
		});  
	});  
</script>

css

css animation

animate

css safari debug

safari c’est de la bite

css reset checkbox

input[type="checkbox"] {
	-webkit-appearance: none;
	-moz-appearance: none;
	-ms-appearance: none;
}

css reset input number

input[type="number"] {
	-webkit-appearance: textfield;
	-moz-appearance: textfield;
	appearance: textfield;
}
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
	// -webkit-appearance: none;
	cursor: pointer;
	opacity: 0;
}

reset

html, body{
	margin: 0;
	padding: 0;
}
*, *:before, *:after{
	box-sizing: border-box;
}

//----------------------------
a{
	text-decoration: none;
}
li{
	list-decoration: none;
}
.clearfix::after {
    content: "";
    clear: both;
    display: table;
}

smooth scroll

html {
	scroll-behavior: smooth;
	scroll-padding-top: 70px; /* height of sticky header, because the header hides the content when jumping to it */
}

parallax

.parallax {
	background-image:  url(../img/bgimg.jpg);
	height:  100vh;
	background-attachment:  fixed;
	background-repeat:  no-repeat;
	background-position:  top;
	background-size:  cover;
	position:  relative;
}

triangle

content:  '';
width:  0px;
height:  0px;
border-top:  30px solid  #19cb4400;
border-bottom:  30px solid  #582cd100;
border-left:  30px solid  #e17a7a;
/* border-right:  30px solid  yellow; */
position:  absolute;
right:  -30px;
top:  20%;

img dans un :before/:after

h2:before{
	content: '';
    background-image: url(../img/img.svg);
    background-size: 32px 32px;
    display: inline-block;
    width: 32px;
    height: 32px;
    background-repeat: no-repeat;
    padding: 0 7px;
}

img rectangle -> ronde

<div>
  <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/9425/kitten.jpg" alt="miaou" />
</div>
div {
  display: inline-block;
  border: 2px dotted orange;
  width: 250px;
  height: 250px;
  border-radius: 50%;
  overflow: hidden;
}
img {
  width: inherit;
  height: inherit;
  border-radius: inherit;
}

/* Bonus : keep aspect-ratio */ 
img {
  object-fit: cover;
  object-position: center center;
}

custom slick dots

.slick-dots {
	display: flex;
	justify-content: center;
	margin: 0;
	padding: 10px 0;
	list-style-type: none;
}
	
.slick-dots li {
	margin: 0 0.25rem;
}
	
.slick-dots button {
	display: block;
	width: 10px;
	height: 10px;
	padding: 0;
	border: none;
	border-radius: 100%;
	background-color: #a7a9ac;
	text-indent: -9999px;
}

.slick-dots li.slick-active button {
	background-color: #414042;
}

slick height

.slick-slide {
   height:200px;
}

.slick-slide img {
   height:200px;
}

barre scroll

::-webkit-scrollbar {
  width: 12px; 
}

::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3); 
}

::-webkit-scrollbar-thumb {
  background: #C4FE00;
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.5); 
}

::selection {
    background: #00000087;
    color: #c4fe00;
}
::-moz-selection {
    background: #00000087;
    color: #c4fe00;
}

css center

how to center in css

css mix-blend-mod hover

.element-container
  &:hover
    &::before,
    &::after
      max-height: 100%
			
  &::before,
  &::after
    content: ''
    position: absolute
    display: block
    bottom: 0
    left: 0
    width: 100%
    height: 100%
    max-height: 0
    transition: all  ease-in-out  .8s

  &::before
    background-color: white
    mix-blend-mode: difference
    z-index: 1

  &::after
    background-color: adjust-hue(#E5007D,  180)
    mix-blend-mode: multiply

Sass max() min() err

max-height: #{"min(50vh, 500px)"}
font-size: #{"max(1em, 1.25vw)"}

font-size: Max(1em, 1.25vw)

JS

js modifier une page

javascript:document.body.contentEditable = 'true';
document.designMode='on'; void 0

js copy to clipboard

style :

/* copyToClipboard */
.copy {
  cursor: pointer;
}
.copied {
  position: relative;
}
.copied::after {
  content: "Copié !";
  position: absolute;
  top: 50%;
  right: 0;
  color: white;
  padding: 5px 10px;
  background-color: #333;
  border-radius: 5px;
  transform: translate(110%, -50%);
}

code :

$('.copy').on('click',  function()  {
  navigator.clipboard.writeText($(this)[0].innerText);
  $(this).addClass('copied');
  setTimeout(function(){
    $('.copy').removeClass('copied');
  },  2000);
});

js console.log custom

console.log('%c Lol',  "background: #74cebd; color: white; font-size: 3em; padding:50px;");

js scroll reveal

const observer =  new  IntersectionObserver(entries  =>  {
	entries.forEach(entry  =>  {
		if (entry.isIntersecting) {
			entry.target.classList.add('.class');
		}  else  {
			entry.target.classList.remove('.class');
		}
	});
});

document.querySelectorAll('.class').forEach(function(elm)  {
	observer.observe(elm);
})

jQuery div qui change onchange

$('body').on('DOMSubtreeModified',  '#ma-div',  function(){
	console.log('au change de #ma-div')
});

Js throttle

function throttle(callback, delay) {
  var last;
  var timer;
  return function () {
    var context = this;
    var now = +new Date();
    var args = arguments;
    if (last && now < last + delay) {
      clearTimeout(timer);
      timer = setTimeout(function () {
        last = now;
        callback.apply(context, args);
      }, delay);
    } else {
      last = now;
      callback.apply(context, args);
    }
  };
}
function debounce(callback, delay) {
  var timer;
  return function () {
    var args = arguments;
    var context = this;
    clearTimeout(timer);
    timer = setTimeout(function () {
      callback.apply(context, args);
    }, delay);
  };
}

Js sous chaine de caractère

var string =  "ABCD"

string.includes('AB') // true

string.includes('ABCJ K QG') // false

jQuery Hover iOS

$('body').attr('ontouchstart','');

jQuery Smooth Back to top

$("#toTop").click(function() {
  $("html, body").animate({
    scrollTop: 0
  }, 1000);
});

jQuery video start au hover

$('.video-hover-start video').trigger("pause");
$('.video-hover-start video').mouseover(function(){
	$('.video-hover-start video').trigger("pause");
	$(this).trigger("play");
});

jQuery add class after scroll

$(document).scroll(function  ()  {
  var $nav =  $(".header")
  $nav.toggleClass('scrolled',  $(this).scrollTop() >  200);
});

js natif récupérer un paramètre dans une url

https://yoururl.com/?form=monparametre&autre=autreparametre

function findGetParameter(parameterName) {
	    var result = null,
	        tmp = [];
	    location.search
	        .substr(1)
	        .split("&")
	        .forEach(function (item) {
	          tmp = item.split("=");
	          if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
	        });
	    return result;
	}

V2

function findGetParameter(parameterName) { 
	const url = new URL(window.location.href);
	return url.searchParams.getAll(parameterName); 
}

Utilisation :

const filter = findGetParameter('filter');

if(filter != null) { 
	filter.forEach(filter => { 
		console.log(filter) 
	}) 
}
function  setGetParameter(parameterName,  parameterValues)  {
	const url =  new  URL(window.location.href);
	url.searchParams.delete(parameterName);
	if (Array.isArray(parameterValues)) {
		parameterValues.forEach(value  =>  {
		url.searchParams.append(parameterName, value);
	});
	}  else  {
		url.searchParams.append(parameterName, parameterValues);
	}
	history.pushState({},  '', url.toString());
}
function  deleteGetParameter(parameterName)  {
	const url =  new  URL(window.location.href);
	url.searchParams.delete(parameterName);
	history.pushState({},  '', url.toString());
}
function  deleteValueGetParameter(parameterName,  parameterValues)  {
	const url =  new  URL(window.location.href);
	const currentValues = url.searchParams.getAll(parameterName);
	const updatedValues = currentValues.filter(value  => value !== parameterValues);
	url.searchParams.set(parameterName, updatedValues.join(','));
	history.pushState({},  '', url.toString());
}

js natif gg AdWords conversion formulaire

window.onload = function(){
	var contactForm = document.querySelector(".webform-client-form-180");
    if(contactForm){ contactForm.onsubmit = function() { gtag_report_conversion(); } }		
}
function gtag_report_conversion(url) {
  var callback = function () {
    if (typeof(url) != 'undefined') {
      window.location = url;
    }
  };
  gtag('event', 'conversion', {
      'send_to': 'AW-xxxxxxx/xxxxxx',
      'event_callback': callback
  });
  return false;
}

js natif navigateur

 // Opera 8.0+
    var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;

    // Firefox 1.0+
    var isFirefox = typeof InstallTrigger !== 'undefined';

    // Safari 3.0+ "[object HTMLElementConstructor]" 
    var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || safari.pushNotification);

    // Internet Explorer 6-11
    var isIE = /*@cc_on!@*/false || !!document.documentMode;

    // Edge 20+
    var isEdge = !isIE && !!window.StyleMedia;

    // Chrome 1+
    var isChrome = !!window.chrome && !!window.chrome.webstore;

    // Blink engine detection
    var isBlink = (isChrome || isOpera) && !!window.CSS;

slick slider flex

*
	min-height: 0
	min-width: 0

js share btn

$('.share').on('click', async () => {
  let title = $('h1')[0].innerText;
  let url = window.location.href;

  let shareData = {
    title: title,
    url: url
  }

  if (navigator.canShare) {
    try {
      await navigator.share(shareData);
    } catch (err) {
      resultPara.textContent = `Error: ${err}`;
    }
  }
});

js imask

imask

js pop-up

pop-up

js feed insta

feed insta

js Tippy

hover tooltype

js Cookies

cookies

js Three

3D js

js intro (tuto)

Intro sur plusieurs pages

js isotop

Isotop (tri par class)

js prismjs

prismjs

js ripples

Ripples

js oo function lol

intégration html

<div id="lol"></div>
<script src="../js/lol.js"></script>
<script>
      const url = '../music/harlem-shake.mp3'
jQuery('#lol').click(function() {
      new HarlemShake({ singleDancer: 'html'}, url).start()
})
</script>

lol.js

"use strict";

class HarlemShake {
  constructor ({ singleDancer = 'body', allDancer = ['p', 'img', 'a', 'label'] }, soundUrl) {
    this.singleDancer = singleDancer;
    this.allDancer = allDancer;
    this.soundUrl = null;

    // Check if the soundUrl is correct.
    if (!soundUrl || typeof soundUrl !== 'string' || soundUrl.length === 0) {
      console.error('[HarlemShake:constructor] Please use a valide string for soundUrl !');
    } else {
      this.soundUrl = soundUrl;
    }

    addCss();
  }

  start () {
    return new Promise(async resolve => {
      if (this.soundUrl) {
        this.addAndPlayMusic();
    
        // Start to play the part with the single 'dancer'.
        await this.singleAnimation();
      
        for (let i = 0; i < 18; i++) {
          await sleep(800);
          this.bordel();
        }
    
        // Reload the web page for avoid all changes.
        location.reload();
        resolve(true);
      } else {
        console.error('[HarlemShake:start] soundUrl isn\'t valide !', this.soundUrl);
        resolve(false);
      }
    });
  }

  addAndPlayMusic () {
    const body = document.querySelector('body');
  
    if (body) {
      const audio = document.createElement('audio');
      audio.src = this.soundUrl;
      audio.autoplay = true;
  
      body.append(audio);
    }
  }

  singleAnimation () {
    return new Promise(async resolve => {
      const animations = [
        { name: 'pulse', time: 1000 },
        { name: 'flash', time: 1000 },
        { name: 'shake', time: 1000 },
        { name: 'swing', time: 1000 },
        { name: 'tada', time: 1000 },
        { name: 'wobble', time: 1000 },
        { name: 'jello', time: 1000 },
        { name: 'bounce', time: 1500 },
        { name: 'flip', time: 1500 },
        { name: 'rollOut', time: 2000 },
        { name: 'rollIn', time: 1000 },
        { name: 'zoomIn', time: 1000 },
        { name: 'zoomOut', time: 1000 },
        { name: 'hinge', time: 1000 },
        { name: 'slideOutUp', time: 1000 },
        { name: 'slideInUp', time: 1000 },
        { name: 'rotateOut', time: 1000 }
      ];
    
      const element = document.querySelector(this.singleDancer);
  
      if (element) {
        for (var i = 0; i < animations.length; i++) {
          const animation = animations[i];
  
          element.classList.add('animated');
          element.classList.add(animation.name);
    
          await sleep(animation.time);
    
          element.classList.remove('animated');
          element.classList.remove(animation.name);
        }
      }
  
      resolve(true);
    });
  }

  bordel () {
    const arrayElement = document.querySelectorAll(this.allDancer.join());
  
    const arrayAnimations = ['bounce', 'flash', 'pulse', 'rubberBand', 'shake', 'swing'
    , 'tada', 'wobble', 'jello', 'bounceIn', 'bounceInDown', 'bounceInLeft', 'fadeIn', 'fadeInDown',
    , 'fadeInDownBig', 'fadeInLeft', 'flip', 'flipInX', 'flipInY', 'lightSpeedOut', 'rotateIn', 'rotateInDownLeft', 
    'rotateInDownRight', 'slideOutLeft', 'slideOutRight', 'zoomInUp',
    'zoomOut', 'zoomOutDown', 'hinge', 'rollIn'];
  
    arrayElement.forEach(element => {
      const indiceRandomAnimation = Math.floor(((Math.random() * 10000 ) % arrayAnimations.length));
      element.classList.add('animated');
      element.classList.add(arrayAnimations[indiceRandomAnimation]);

      // Set random color
      element.style.color = randomColor();
      element.style.backgroundColor = randomColor();
  
      setTimeout(() => {
        // Remove class
        element.classList.remove('animated');
        element.classList.remove(arrayAnimations[indiceRandomAnimation]);
      }, 700);
    });
  }
}

/***** UTILS *****/

function sleep (time) {
  return new Promise(resolve => { setTimeout(resolve, time) });
}

function randomColor () {
  return `rgb(${random()}, ${random()}, ${random()})`;
}

function random () {
  return Math.floor(((Math.random() * 4242 ) % 256));
}

function addCss () {
  const head = document.querySelector('head');

  if (head) {
    const link = document.createElement('link');
    link.setAttribute('rel', 'stylesheet');
    link.setAttribute('href', 'https://cdn.jsdelivr.net/npm/animate.css@3.5.2/animate.min.css');

    head.append(link);
  }
}

module.exports = HarlemShake;

js phrase aléatoire

var randPhrase = ["phrase 1", "phrase2", "phrase3", "phrase4"];
 	randPhrase = randPhrase[Math.floor(Math.random()*4)];
 	console.log(randPhrase);

Multi Scroll js

Syncscroll

<div class="syncscroll" name="myElements">
    First big text goes here...
</div>

<div class="syncscroll" name="myElements">
    Second big text goes there...
</div>

momentjs(time)
nice-select(select)
swiperjs(slider)
js-cookie

PHP

langue

if (ICL_LANGUAGE_CODE == 'fr'){
	echo do_shortcode('[sg_popup id=2739]');
} 
else {
	echo do_shortcode('[sg_popup id=2750]');	
}

ternary operator

https://pear.php.net/manual/en/rfc.cs-enhancements.ternaryoperators.php

Gulp

const gulp = require('gulp');
const sass = require('gulp-sass'); 
const sourcemaps = require('gulp-sourcemaps'); 
const pug = require('gulp-pug');
const pump = require('pump')
const uglify = require('gulp-uglify');
const inline = require('gulp-file-inline');
const postcss = require('gulp-postcss');
const autoprefixer = require('autoprefixer');
const cssnano = require('cssnano');
const replace = require('gulp-replace');

//----------------------------------------
// compile

// compile sass
gulp.task('sass', function () {
  return gulp.src('./sass/*.scss')
  	.pipe(sourcemaps.init())
  	.pipe(sass().on('error', sass.logError))
  	.pipe(sourcemaps.write())
    .pipe(gulp.dest('./css'));
});

// compile pug
gulp.task('pug', function () {
  return gulp.src('./views/*.pug')
    .pipe(pug())
    .pipe(gulp.dest('./views/html'))
});

// watch sass => sass
gulp.task('sass:watch', function () {
  gulp.watch('./sass/*.scss', ['sass']);
});

// watch pug =>pug
gulp.task('pug:watch', function () {
  gulp.watch('./views/**/*.pug', ['pug']);
});

// gulp watch
gulp.task('watch', ['sass:watch', 'pug:watch']);

//gulp
gulp.task('default', ['watch']);


//----------------------------------------
// build dist


// build html for dist
gulp.task('build:html', function () {
  return gulp.src('./views/*.pug')
    .pipe(pug())
    .pipe(replace('../../sass', '../../css'))
    .pipe(replace('../../', ''))
    .pipe(replace('../', ''))
    .pipe(gulp.dest('./dist'));
})

// build css for dist
gulp.task('build:css', function () {
    var plugins = [
        autoprefixer({browsers: ['last 2 version']}),
        cssnano()
    ];
    return gulp.src('./sass/*')
    .pipe(sass())
    .pipe(postcss(plugins))
    .pipe(inline())
    .pipe(gulp.dest('./dist/css'));
})

// build js for dist
gulp.task('build:js', function () {
  pump([
        gulp.src('./js/*.js'),
        uglify(),
        gulp.dest('./dist/js')
    ]);
})

//build image for dist
gulp.task('build:img', function () {
    gulp.src('./img/**')
      .pipe(gulp.dest('./dist/img'))
})

// gulp build
gulp.task('build', ['build:html', 'build:css', 'build:js', 'build:img']);

// gulp b (build)
gulp.task('b', ['build']);

Google

URL tel

https://hostname.tld/path/#google-wcc-debug

Favicon

http://www.google.com/s2/favicons?domain=yoururl.com

Mail

mail de maintenance

mail nouvelle adresse mail

Bonjour,

  Voici les accès à la boîte mail demandée :
    
  Nom d'utilisateur : xxxxxxx@xxxxxx.xx
  Mot de Passe : XXXXXXXXXX

  Vous pouvez utiliser ces identifiants pour vous connecter directement à votre boîte email sur le serveur en allant à l'adresse suivante : https://mail.ovh.net/roundcube

  Ou alors ajouter ces adresses sur votre logiciel de messagerie ordinateur ou mobile, à l'aide des paramètres suivants :

  Serveur entrant (IMAP) : http://ssl0.ovh.net/
  Port IMAP : 995 (si SSL activé), 110 sinon

  Serveur sortant (SMTP) : http://ssl0.ovh.net/
  Port SMTP : 465 (si SSL activé), 587 sinon

  Pour installer ces comptes emails sur ton ordinateur ou sur ton téléphone, voici 2 guides expliquant pas à pas comment faire :

  Configuration sur iPhone : https://docs.ovh.com/fr/emails/mail-mutualise-guide-configuration-iphone-ios-91/
  Configuration sur Outlook : https://docs.ovh.com/fr/emails/mail-mutualise-guide-configuration-outlook-2013/

  Je reste à votre disposition.

  Cordialement,
  Léandre
  

mail nouvelle signature mail

Bonjour,

  Voici le lien pour la signature mail : xxxxxxxxxxxxxxx

  Pour l'installer dans votre boîte mail, il faut :
  - Vous rendre à l'adresse ci-dessus,
  - Copier le contenue de la page (ctrl+a puis ctrl+c),
  - Coller (ctrl+v) dans les paramètres de signature de votre boite mail.
  
  Je reste à votre disposition.

  Cordialement,
  Léandre
  

WordPress

aide WPFR

WPFR

template

Inbox(dashboard)
Talon(entreprise)
Sydney(entreprise)
Hestia(entreprise)
Indra(entreprise)
Shop-isle(shop)
Ignis(portfolio)
Eris(portfolio)
Hamilton(portfolio)
CoupLite(blog)
Curver(blog)

body

<body <?php body_class(); ?>>

Récupérer les CPT

$posts = get_posts([
  'post_type' => 'appartements',
  'category' => $category,
  'post_status' => 'publish',
  'numberposts' => -1,
  'tax_query' => [
    [
      'taxonomy' => 'category',
	  'field' => 'slug',
	  'terms' => $category,
	  'operator' => 'IN',
    ]
  ],
  'suppress_filters' => 0, // Pour ne garder que les postes dans la langue en cours
  'orderby' => 'menu_order', 
  'sort_order' => 'asc',
]);

Woocommerce

Categories = page

Here’s my setup (it does not require any additional plugins or code edits) A couple of installed plugins are WP Rocket and Yoast on which I’ll focus in this thread.

  1. WP Dashboard->Settings->Permalinks

  2. Select “Custom Structure” and enter /%category%/%postname%/ in the field

  3. On the same page, change “Category base” to a single dot. “.” (no quotes, just a single dot/period/full stop

I have Yoast installed, which I had set up to override the permalink settings, but I believe this messed up my task at hand.

  1. WP Dashboard->SEO->Advanced->Permalinks(tab)

  2. “Change URLs->Strip the category base…” = Keep

  3. Then you need to clear the cache. I use WP Rocket for caching, so I flushed the cache and everything now works the way it should.

get-product

// functions.php
add_theme_support( 'woocommerce' );
// woocommerce.php 
<?php 
get_header(); 

if ( is_singular( 'product') ) { 
  woocommerce_content(); 
} else { 
  wp_get_template( 'archive-product.php' ); 
  } 
  
get_footer(); 
?>
/* main.css (conflit bootstrape) */
.woocommerce .col2-set .col-1, .woocommerce-page .col2-set .col-1,.woocommerce .col2-set .col-2, .woocommerce-page .col2-set .col-2 { 
  max-width: unset; 
  padding: 0; 
}

Define

define( 'WP_HOME', 'https://mon-url.com/' )
define( 'WP_SITEURL', 'https://mon-url.com/' )

Pour utiliser les images en .svg

// A ajouter dans functions.php

function cc_mime_types($mimes) {
 $mimes['svg'] = 'image/svg+xml';
 return $mimes;
}
add_filter('upload_mimes', 'cc_mime_types');
<!-- A ajouter dans le svg -->
<?xml version="1.0" encoding="utf-8"?>

Mettre le site dans la langue du navigateur

A ajouter dans le .htaccess

#Si navigateur défini sur anglais 'en'
#Insensible à la casse ([NC])
RewriteCond %{HTTP:Accept-Language} ^en [NC]
#Rediriger l'utilisateur vers /en/
#Redirection de type 301 (permanente)
RewriteRule ^$ /en/ [L,R=301]

PHP redirection 301

<?php header('Location: https://mon-url.com/', 301); ?>

Modifier en fonction de la langue

if( ICL_LANGUAGE_CODE == "fr"){ }
function  mlurl($id){
	return  get_permalink(  icl_object_id($id,  'page',  true)  );  // Get the URL of a translated page (current language displayed)
}

// Get the link of the current translated page
function  switchLanguageTo($lang)  {
	return  apply_filters(  'wpml_permalink',  get_the_permalink()  ,  $lang  );
}

Pour créer des thumbnails personnalisé

add_action( 'after_setup_theme', 'wpdocs_theme_setup' ); 
function wpdocs_theme_setup() { 
	add_image_size( 'category-thumb', 300 ); // 300 pixels wide (and unlimited height) 
	add_image_size( 'homepage-thumb', 220, 180, true ); // (true = cropped) 
} 
// Regénérer les images après
// Plugin pour recharger les thumbnails: https://wordpress.org/plugins/regenerate-thumbnails/

Pour trad les texte avec _e

<?php _e("Texte blabla","nom-du-site"); ?>

Charger les fonctions php de wp dans un fichier

// Importing WP functions in custom php file  
require($_SERVER['DOCUMENT_ROOT'].'/wp-load.php');

appeler le css et js

//dans le fonction.php
wp_enqueue_style( 'slick-css', get_stylesheet_directory_uri() . '/assets/css/slick.css', null, '1.0.0');
wp_enqueue_script( 'slick', get_stylesheet_directory_uri() . '/assets/js/slick.min.js', null, '1.0.0', true );
wp_enqueue_script( 'main', get_stylesheet_directory_uri() . '/assets/js/main.js', null, '1.0.0', true );
jQuery(document).ready(function()  {  
 
});

enlever les notifs du back office

//notice back office
/* Supprimer les notifications du core */
add_filter('pre_site_transient_update_core',  create_function('$a',  "return null;"));
/* Supprimer les notifications de thèmes */
remove_action('load-update-core.php',  'wp_update_themes');
add_filter('pre_site_transient_update_themes',  create_function('$a',  "return null;"));
/* Supprimer les notifications de plugins */
remove_action('load-update-core.php',  'wp_update_plugins');
add_filter('pre_site_transient_update_plugins',  create_function('$a',  "return null;"));

ACF repeteur

<?php $nom_du_repeteur_s = get_field('nom_du_repeteur'); ?>

<?php foreach($nom_du_repeteur_s as $nom_du_repeteur) : ?>
	<div class="txt"><?= $nom_du_repeteut['array(var_dump($nom_du_repeteur_s))'] ?></div>
	<div class="img"><img src"<?= $nom_du_repeteut['url'] ?>"></div>
<?php endforeach; ?>
<?php
	if( have_rows('nom_du_repeteur') ):
		while ( have_rows('nom_du_repeteur') ) : the_row(); ?>
	     // exemple texte
		     <h1><?php the_sub_field('titre'); ?></h1>
		 
		 // exemple image
	         <img src="<?php echo get_sub_field('image')['url']; ?>">
<?php
		endwhile;
	else :
	// nothing
	endif;
?>

Contact form 7 custom

  1. Créer un contact form
  2. Intégrer dans config.php (remove br)
// REMOVE BR CONTACT FORM 7 
define('WPCF7_AUTOP', false );
  1. Utiliser le formulaire existant en remplaçant les input avec les short-code
<!-- exemple -->
<input class="clearfix" type="text" placeholder="Nom">
[text* nom class:clearfix placeholder "Nom"]
<!-- c.f. : contact form 7 -->
  1. Intégrer le short-code à la place de la balise
/* exemple */
<?php echo do_shortcode('[contact-form-7 id="xx" title="contact" html_class="class_du_form"]'); ?>
  1. Ajouter input caché
/* exemple */
<?php echo do_shortcode('[contact-form-7 id="xx" title="contact" inputcaché="'.$var.'" html_class="class_du_form"]'); ?>

/* ajouter dans fonction.php */
<?php
add_action('acf/init', 'my_acf_init');

// PASS PARAM TO CONTACT FORM 7 SHORTCODE
add_filter( 'shortcode_atts_wpcf7', 'custom_shortcode_atts_wpcf7_filter', 10, 3 );
function custom_shortcode_atts_wpcf7_filter( $out, $pairs, $atts ) {
    $my_attr = 'inputcaché';
     if ( isset( $atts[$my_attr] ) ) {
        $out[$my_attr] = $atts[$my_attr];
    }
    return $out;
}
?>
  1. Ajouter dans contact form 7
[text inputcaché default:shortcode_attr]

CF7

// CONTACT FORM 7 //  
// Ajout d'un ou plusieurs paramètre de shortcode dans CF7  
add_filter( 'wpcf7_form_elements', 'do_shortcode' ); // Ajoute la possibilité de mettre des shortcode dans le corps de CF7  
  
function input_hidden( $atts ) {  
$data = $_GET['data'];  
return '<input type="hidden" name="'.$atts["name"].'" value="'.$data.'">';  
}  
add_shortcode( 'cf7_hidden', 'input_hidden' ); // Créer un custom shortcode  
// [cf7_hidden name="url"] // <-- A ajouter dans le corps du formulaire de CF7  
  
add_filter( 'wpcf7_form_elements', 'do_shortcode' );  
function input_hidden( $atts ) {  
$current_link = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";  
$lang = strpos($current_link, '.com/en/') !== false ? "en" : "fr";  
  
return '<input type="hidden" name="url" value="'.$current_link.'">'.'<input type="hidden" name="lang" value="'.$lang.'">';  
}  
add_shortcode( 'cf7_hidden', 'input_hidden' );

Problème bdd

remplacer utf8mb64 par utf8
remplacer utf8mb4_unicode_520_c par utf8_unicode_ci

Changer le mdp wp via phpmyadmin

  1. Chercher wp_users dans la bdd
  2. Utiliser passwordtool
  3. Remplacer user_pass par le nouveau
    En plus passer un utilisateur en admin

Ajouter des fonts google sur wp

/* Dans fonction.php */
function add_google_fonts(){ 
wp_enqueue_style( 'google_web_fonts', 'https://fonts.googleapis.com/css?family=Open+Sans|Roboto' ); 
} 
add_action( 'wp_enqueue_scripts', 'add_google_fonts' );

custom admin interface utilities

grid pour les repeteur

.special-table.sp .acf-repeater .acf-table tbody {
  display: flex;
  flex-wrap: wrap;
}
.special-table.sp .acf-repeater .acf-table .acf-row {
  width: 100%;
}

.special-table.sp-2 .acf-repeater .acf-table tbody {
  display: grid;
  grid-template-columns: repeat(auto-fill,minmax(50%, 1fr));
}

.special-table.sp-3 .acf-repeater .acf-table tbody {
  display: grid;
  grid-template-columns: repeat(auto-fill,minmax(33%, 1fr));
}

.special-table.sp-4 .acf-repeater .acf-table tbody {
  display: grid;
  grid-template-columns: repeat(auto-fill,minmax(25%, 1fr));
}

.special-table .acf-fields {
  width: 100%;
}

retract all white space & picto deco

$('.layout').each(function() {
    var dataLayout = $(this).data('layout')
    if(dataLayout == 'white_space' || dataLayout == 'picto_deco') {
        $(this).addClass('-collapsed')
    }
}); 

css

/* copyToClipboard */
.copy {
  cursor: pointer;
}
.copied {
  position: relative;
}
.copied::after {
  content: "Copié !";
  position: absolute;
  top: 50%;
  right: 0;
  color: white;
  padding: 5px 10px;
  background-color: #333;
  border-radius: 5px;
  transform: translate(110%, -50%);
}

js

// copyToClipboard
  $('.copy').on('click', function() {
    navigator.clipboard.writeText($(this)[0].innerText);
    $(this).addClass('copied');
    setTimeout(function(){
    	$('.copy').removeClass('copied');
    }, 2000);
  });

Multisite fix add users

Ajouter dans la bdd :
Image bug multisite users

Solution trouvée ici

Img wp

<?= wp_img($img['id'], 'large', ['loading'=>'eager', 'class'=>'test']) ?>

Mamp

Nom de domaine en local

Tools

Extensions

infinite tab manager
wildfire(automation)
wappanalyzer(analyse des outils utilisés sur un site
css used
toby

Sublime text 3

// key biding (-> Preferences>key biding)
{ "keys": ["super+'"], "command": "insert_snippet", "args":
		{"contents": "<?php _e(\"${1:}$SELECTION\",\"trad\"); ?>${0}"}
},

VS code

ctrl+shift+p > snippet > nouveau snippet global

"e_wpml": {  
	"prefix": "_e(",  
	"body": [  
		"<?php _e(\"$TM_SELECTED_TEXT${1:}\",\"merci-creative-trad\"); ?>"  
	],  
	"description": "Encloses static text in WPML fonction"  
},

dans préférences > raccourcis clavier > petit fichier en haut à droite

{
	"key":  "cmd+r",
	"command":  "editor.action.insertSnippet",
	"args":  {
		"name":  "e_wpml"
	}
},

Help

ovh backup

Mdp

https://pwpush.com/

Vérifier site web

Securitytrails(DNS)
Xml-sitemaps(sitemap)
Axeptio(cookie & RGPD)
Erreur 504 vérification
Lien cassé
Responsive all screen
Responsive mobile
Suppresion de données sur google
Web.dev(ligthouse)
Inspectlet(interactions utilisateurs)
Spyfu(analyse de site concurents)
Ubersuggest(mots SEO)
Varvy(SEO)
Metatags(meta description)
a11y (accessibility)

Réseaux sociaux

sharelink(partage réseaux sociaux)
Facebook publication

Animations

SVGator
lottiefiles(svg animés)
transition sans rechargement de la page
Accordion
Fullpage (scroll slider js)
Scroll reveal (animation js)
Slick (slider js)
Menu Hamburger
Menu Hamburger 2
Parallax
Hover effect
Nicescroll(scroll)
Son qui lit les textes
sticky

Typo & image

Nice select
colormind
DevTools.best
Pomodoro Timer Online - Pomofocus
open doodles
uispace
iradesign
freellustrations
blush
Many pixels
draw kit
ls graphics
sketch app sources
uplabs
Milanote
Graph
web design inspiration
template à imprimer
dialogflow(chatbot)
mp4-to-gif
cut mp4
svg cleaner
Clippy(CSS geometrie)
UI components
html to pdf
aconvert
Beefree(newsletter)
Rawpixel(mockup)
Metapicz(EXIF)
Picular(color)
custom-ecriture
Uimovement(inspiration)
pdf2go(modifier pdf)
ilovePDF
qrcode-monkey
ouch(picto)
Screely(mockup)
Graphicburger
emoji(ctrl+c)
Badgen(badge github)
Shrinkme(réduire les images)
Ezgif(réduire les gifs)
StockSnap (img)
Unsplash (img)
Pexels(img)
Finda(img)
Png 360°(img)
Coverr(video)
Lifeovids(video)
Icones8(picto)
Pixelify (typo)
Font combination(typo)
Lapa ninja(cours)
QR code
rgb to hex
Couleur inspiration
Coolor
Colorbox
Trendy(palette de couleur)
Gradient
Coolhue(gradient)
Material shadow
Undraw(picto flat)
Collectui(landingpage)
Uidb(landingpage)
Smash(wetransfer français)
transfernow(wetransfer français)
Replit

Music

Jamendo(music libre de droit)
CCmixter(music libre de droit)
CCtrax(music libre de droit)
Tunefind(retrouver musique d’un film)

Grid

Flexbox grid
TerminalMaterializeCSS

DatePicker

Litepicker

regExr (chaines de caractère)

regExr

Html

prettify html
Case converter
Mysignature(signatures mails)

Support client

support

Hébergement

DNS
ngrok (partage de localhost)
mkcert (https en local)