Snippet per Wordpress

QUESTO SNIPPET CONTIENE PIÙ PARTI

Codice da aggiungere/modificare nel wp-config

// Enable WP_DEBUG mode
define( 'WP_DEBUG', true );

// Enable Debug logging to the /wp-content/debug.log file
define( 'WP_DEBUG_LOG', true );

// Disable display of errors and warnings
define( 'WP_DEBUG_DISPLAY', false );
@ini_set( 'display_errors', 0 );

Codice da aggiungere nel function, da richiamare _log("testo che voglio vedere stampato in debug")

 if (!function_exists('_log')) {
  function _log($log) {
      if (true === WP_DEBUG) {
          if (is_array($log) || is_object($log)) {
              error_log(print_r($log, true));
          } else {
              error_log($log);
          }
      }
  }
}

function register_my_menus() {
  register_nav_menus(
    array(
      'menu-main-home-2' => __( 'Main menu Home 2' ),
    )
  );
}
add_action( 'init', 'register_my_menus' );

Maggiori spiegazioni qui


/* aggiunta dei custom fields fra i parametri della search di wp, fonte https://adambalee.com/search-wordpress-by-custom-fields-without-a-plugin/ */
/**
* Extend WordPress search to include custom fields
*
* https://adambalee.com
*/

/**
* Join posts and postmeta tables
*
* http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_join
*/
function cf_search_join(  ) {
  global ;

  if ( is_search() ) {    
       .=' LEFT JOIN '.. ' ON '.  . '.ID = ' .  . '.post_id ';
  }

  return ;
}
add_filter('posts_join', 'cf_search_join' );

/**
* Modify the search query with posts_where
*
* http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_where
*/
function cf_search_where(  ) {
  global , ;

  if ( is_search() ) {
       = preg_replace(
          "/\(\s*"..".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
          "("..".post_title LIKE $1) OR ("..".meta_value LIKE $1)",  );
  }

  return ;
}
add_filter( 'posts_where', 'cf_search_where' );

/**
* Prevent duplicates
*
* http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_distinct
*/
function cf_search_distinct(  ) {
  global ;

  if ( is_search() ) {
      return "DISTINCT";
  }

  return ;
}
add_filter( 'posts_distinct', 'cf_search_distinct' );

filemtime ricava la data di ultima del file specificato, in questo caso, utilizziamo questo fatto per evitare la cache aggiungendo il valore della data come variabile get del link css

$ver = filemtime(get_stylesheet_directory() . '/css/nome-file-css.css');

Prende la stylesheet directory URI del tema attivo, ulteriori spiegazioni qui

<?php echo get_stylesheet_directory_uri() ?>  /percorso.formato 

Incollare questo codice dentro il wp-config per attivare il debug, il file di debug sarà creato dentro wp-content

define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );

if (is_page_template("quiz-template.php")){
    //fai cose
}

Rimuove la formattazione di contact form nel front end, maggiori informazioni qui

add_filter('wpcf7_autop_or_not', '__return_false');

Da modificare, eventuale guida qui, utilizzato su daureka.it e messo nel function.php

/* questo filtro aggiungge i file richiesti dagli utenti tramite il form alla mail che riceveranno */
/* https://stackoverflow.com/questions/48189010/dynamically-attaching-file-to-contact-form-7-e-mail */
add_filter('wpcf7_mail_components', 'custom_wpcf7_mail_components');
    function custom_wpcf7_mail_components($components)
    {
        //Get current form
        $wpcf7 = WPCF7_ContactForm::get_current();
        $attachment_file_path = '';
        //check the relevant form id
        
        /* id dei form che dovranno allegare i file nella mail degli utenti, bisognerà aggiungerne per ciascuna lingua */
        if ($wpcf7->id() == 80) {
          
            // get current SUBMISSION instance
            $submission = WPCF7_Submission::get_instance();
            if ($submission) {
                // get submission data
                $data = $submission->get_posted_data();
                // setup upload directory
                /* $upload_dir = get_stylesheet_directory_uri(); */
                $upload_dir = WP_CONTENT_DIR."/themes/NOME-TEMA-FIGLIO";
                  /*
                  * Form hidden attachment file name Ex: 'ProRail_NA_Gen5.pdf'
                  * You can hard-code the file name or set file name to hidden form field using JavaScript
                  */
                  /* pdf_selezionati è un valore custom non di contact form 7 */
                  $files_name = $data['pdf_selezionati'];
                  //get upload base dir path Ex: {path}/html/app/uploads
                  /* $base_dir = $upload_dir['basedir'];
                  //nome della cartella all'interno di thecontent che contiene i file da allegare */
                  $file_dir = 'pdf';
                  //set attachment full path
                  /* $attachment_file_path = $base_dir .'/'.$file_dir.'/'.$file_name; */
                  /* in base al subjet della mail, stabilisco se allegare i file, questo era utile su DAUREKA perché mandiamo la mail non solo al cliente ma all\utente che compila il form */
                  if ($components['subject'] == 'Daureka - File richiesti Area Utente' || $components['subject'] == 'Daureka - File richiesti Area Fornitori') {
                    foreach ($files_name as $key => $value) {
                      $attachment_file_path.$key = $upload_dir .'/'.$file_dir.'/'.$value.'.pdf'; 
                      $components['attachments'][] = $attachment_file_path.$key;
                    }
                  }
                  //append new file to mail attachments
            }
        }
        /* ob_start();
        var_dump($components);
        error_log(ob_get_clean()); */
        return $components;
    }

Da modificare, aggiungere l'id del form a cui vogliamo applicare questa funzione, DA AGGIUNGERE anche gli ID di eventuali form tradotti

/* aggiunta di un'azione vincolata all'invio del form indicato dall'id*/
document.addEventListener( 'wpcf7mailsent', function( event ) {
    /* 10528, 3258 IDs DEI FORM */
    if(event.detail.contactFormId == '10528' || event.detail.contactFormId == '3258') {
        //fai cose                    
    }
}, false );

[your-email] e [your-name] sono da adattare in base ai campi del form.
'acceptance_as_validation: on' fa comportare le checkbox come gli altri input alla validation, quindi aggiunge il messaggio d'errore rosso

acceptance_as_validation: on
flamingo_email: "[your-email]"
flamingo_name: "[your-name]"
flamingo_subject: "Nome modulo, sarà visualizzato in Flamingo"

<?php get_field('nome_field_impostato_da_wordpress'); ?>

Modificare numero di risultati nella search di default di wordpress

$linkAggiuntivo = get_field('nome_custom_field'); 
$targetBlank = '';
if ($linkAggiuntivo['target'] != ''){
  $targetBlank = "target='_blank'";
};

Aggiungere nel function questo filtro per impedire il ridimensionamento delle immagini da parte di wordpress

add_filter( 'big_image_size_threshold', '__return_false' ); 

Modificare numero di risultati nella search di default di wordpress

function change_wp_search_size($query) {
	if ( $query->is_search && !is_admin() ) // Make sure it is a search page
		$query->query_vars['posts_per_page'] = 12; // Change 10 to the number of posts you would like to show

	return $query; // Return our modified query variables
}
add_filter('pre_get_posts', 'change_wp_search_size'); // Hook our custom function onto the request filter

Da aggiungere prima di get header

wp_redirect(home_url());

Utile ad esempio per contact form

<?php echo do_shortcode('[contact-form-7 id="5" title="Modulo Contattaci"]')?>

Inserire, nel template da non cachare mai, il codice sottostante. Maggiori informazioni qui

define('DONOTCACHEPAGE', true);

QUESTO SNIPPET CONTIENE PIÙ PARTI

codice php

/*IL PADRE DEVE ESSERE header-actions IN POSITION RELATIVE, tema bootscore*/
<div class="langSwitcher">
    <?php 
    function get_custom_lang_code_func() {
        $languages = apply_filters( 'wpml_active_languages', NULL, 'orderby=code&order=desc' );
        if(!empty($languages)){
            //$content = '<ul id="select_lang_switch">';
                $content = '';
                foreach($languages as $l){
                        if($l['language_code']){
                            $selected = '';
                            if($l['active'])
                            $selected = "active";
                        $content .= '<li class="'.$selected. ' wpml-ls-item"><a href="'.$l['url'].'">'.$l['language_code'].'</a></li>';
                        }
                }
            $content .= '';
        }
        return $content;
    }
    ?>  
    <ul>
    <?php echo get_custom_lang_code_func(); ?>
    </ul>
</div>

codice css

.langSwitcher{
    position: absolute;
    cursor: pointer;
    width: 100%;
    left: 0;
    top: 0;
    width: 50px;
    transform: translate(-100%, 0);
    ul{
    padding: 0;
    margin: 0;
    list-style-type: none;
    max-height: 0px;
    overflow: hidden;
    transition: all 0.4s;
    padding-top: 37.6px;
    top:0;
    left: 0;
    background-color:  blue;
    width: 50px;
    border-radius: 5px;
    &.aperta{
        max-height: 80px;
    }
    li{
        transition: all 0.2s;
        min-width: 50px;
        display: flex;
        align-items: center;
        justify-content: center;
        &:hover{
        background-color: green;
        a{
            color: white;
        }
        }
        &.active{
            position: absolute;
            left: 0;
            top: 0px;
            width: 100%;
            pointer-events: none;
            cursor: pointer;
        }
        a{
            font-size: 16px;
            text-transform: uppercase;
            color: red;
            display: flex;
            align-items: center;
            justify-content: center;
            text-decoration: none;
            width: 50px;
            font-weight: 500;
            transition: all 0.4s;
            /* padding: 8px 20px; */
            /* width: 100%; */
            height: 37.6px;
            white-space: nowrap;
        }
    }
    }
}

codice js

$('.langSwitcher').on('click', function() {
    $('.langSwitcher ul').toggleClass("aperta");
});

$paginaDaTradurre = icl_object_id(519, 'page', true); // 519 è l'ID della pagina originale, DA SOSTITUIRE 
$url_pagina_tradotta = get_permalink($paginaDaTradurre );
link

$linguaAttuale = ICL_LANGUAGE_CODE;

<?php _e("frase da tradurre", "nome scelto"); ?>