Supporto » Sviluppare con WordPress » add_rewrite_rule per pagina e campi

Stai visualizzando 15 risposte - dal 1 al 15 (di 15 totali)
  • Per personalizzare l’url devi entrare in Bacheca ->Impostazioni ->Permalink

    Chi ha creato la discussione Alberto

    (@caseuniche)

    Grazie Steve,

    ma … sono entrato in admin-menu > Settings > Permalink > Save Changes
    per rendere effettiva la regola.
    il problema si verifica dopo 🙁

    Ho un log delle regole attive:

    Array ( 
    [attivita/(.*)] => index.php?homeland_properties=$matches[1] 
    [immobile/(.*)] => index.php?homeland_properties=$matches[1] 
    [categoria/(.*)] => index.php?homeland_property_type=$matches[1] 
    [in-affitto] => index.php?homeland_property_status=for-rent 
    [in-vendita] => index.php?homeland_property_status=for-sale 
    <blockquote>[vendita/(.*)] => index.php?pagename=search-property&homeland_property_status=for-sale&homeland_property_type=$matches[1] </blockquote>
    ....
    

    tutte le altre (riferite a CPT e tassonomie) funzionano ma l’ultima
    riferita ad una pagina con parametri
    non funziona 🙁

    Qualche suggerimento ?

    Alberto

    Chi ha creato la discussione Alberto

    (@caseuniche)

    … scusate
    il <blockquote> </blockquote> non esiste (ho cercato solo di evidenziare la regola che non funziona.

    Il log delle regole è:

    Array ( 
    [attivita/(.*)] => index.php?homeland_properties=$matches[1] 
    [immobile/(.*)] => index.php?homeland_properties=$matches[1] 
    [categoria/(.*)] => index.php?homeland_property_type=$matches[1] 
    [in-affitto] => index.php?homeland_property_status=for-rent 
    [in-vendita] => index.php?homeland_property_status=for-sale 
    [vendita/(.*)] => index.php?pagename=search-property&homeland_property_status=for-sale&homeland_property_type=$matches[1]
    ....
    

    In admin-menu > Settings > Permalink > Save Changes cosa hai settato?

    Chi ha creato la discussione Alberto

    (@caseuniche)

    … ho semplicemente clickato Save Changes
    pe rendere effettive le regole.

    come permalink è settato questo:

    Common Setting
    Post name https://custaging.caseuniche.it/sample-post/

    Optional
    Category base: vuoto
    Tag base: vuoto

    Steve, grazie per l’aiuto.

    Alberto

    Devi settare uno di questi e dopo cliccare Salva le modifiche. Provali tutti.

    Schermata-2021-09-13-alle-21-38-17

    Chi ha creato la discussione Alberto

    (@caseuniche)

    🙁 li ho provati tutti … nessuno funziona 🙁
    la situazione è sempre la stessa 🙁

    Fai così: entra nell’articolo Modifica articolo e clicca su Permalink e scrivi il nome che vuoi poi clicca Aggiorna. Vuota la cache e vedrai che nella barra degli indirizzi appare il nome che hai scritto.

    Schermata-2021-09-14-alle-07-25-15<br />online photo<br />

    Ciao @caseuniche,

    il problema potrebbe essere che WordPress non conosce i parametri che aggiungi alla query string e di conseguenza non sa che deve gestirli.

    In questo caso dovresti registrarli usando il filtro “query_vars”.
    Dai un’occhiata a questo esempio: https://developer.wordpress.org/reference/functions/add_rewrite_rule/#comment-3503

    Fatto questo, bisogna capire come questi parametri vengono utilizzati nella pagina, ad esempio se vengono letti per parametrizzare una custom query. Non sapendo com’è fatta la pagina non posso essere più specifico. In linea di principio, comunque, una volta che aggiungi i parametri con il filtro, poi all’interno della pagina puoi leggerli con la funzione “get_query_var()”.

    Spero di essere stato d’aiuto, eventualmente chiedi pure 🙂

    Chi ha creato la discussione Alberto

    (@caseuniche)

    Ciao a tutti,

    Steve92: fatto quanto suggerisci, tutto come prima

    Andrea P.:
    inrealta nel file functions.php del child theme c’è scritto:

    
    add_filter('query_vars', function($qvars){
    		$qvars[] = 'status';
    		$qvars[] = 'type';
    		return $qvars;
    	});
    	add_rewrite_rule( 'vendita/(.*)', 'index.php?pagename=search-property&status=for-sale&type=$matches[1]', 'top' ) ;
    

    qundi su questo punto dovremmo esserci.

    Per qunto riguarda i parametri della query:
    se usi il link
    https://custaging.caseuniche.it/?pagename=search-property&status=for-sale&type=residenziale
    la pagina di arrivo riconosce i parametri e li utilizza
    ma se usi
    https://custaging.caseuniche.it/vendita/residenziale

    nonostante il rewrite impostato e il filtro query_vars
    la pagina non elabora i campi type e status

    Ma cosa sbaglio ??? :-||

    Grazie per l’aiuto,
    Alberto

    Ciao @caseuniche,

    ho recuperato questo frammento da un mio progetto di un po’ di tempo fa:

    
    add_action( 'init', function() {
        add_rewrite_rule( '^calendario/?([^/]*)/?', 'index.php?page_id=68&stagione=$matches[1]', 'top' );
    } );
    

    Rispetto al codice che avevi postato direi un paio di cose:
    – la funzione add_rewrite_rule() deve essere usata nella action “init”. Nel tuo esempio sembrava utilizzata in modo isolato, se non capisco male.
    – nel primo parametro nella funzione prova ad utilizzare la regex che vedi nel mio codice.

    Poi ho un dubbio: nell’url originale vengono passati 3 parametri, mentre in quella “riscritta” ce ne sono solo due. E’ possibile che non essendoci un valore per il parametro “pagename” non vengano considerati gli altri 2 parametri.

    Vedrei meglio una url di questo tipo:
    https://custaging.caseuniche.it/cerca/vendita/residenziale

    Ma non avendo davanti il codice completo non saprei darti indicazioni più precise.
    Facci sapere se fai passi avanti.
    Ciao!

    Chi ha creato la discussione Alberto

    (@caseuniche)

    Caro Andrea,
    grazie per la tua dettagliata risposta.

    Ma il mistero … si infittisce

    + la mia rewrite rule è effettivamente scritta direttamente nel file functions.php
    del tema child

    	add_filter('query_vars', function($qvars){
    		$qvars[] = 'status';
    		$qvars[] = 'type';
    		return $qvars;
    	});
    	add_rewrite_rule( 'vendita/([^/]*)', 'index.php?pagename=search-property&status=for-sale&type=$matches[1]', 'top' ) ;
    	add_rewrite_rule( 'vendiamo/(.*)', 'index.php?pagename=search-property&status=for-sale&type=$matches[1]', 'top' ) ;
    

    e produce la corretta regola quando si fa flush manualmente seguendo il percorso
    admin-menu > Settings > Permalink > Save Changes
    Infatti la ritrovo nell’Array delle regole:

     [attivita/(.*)] => index.php?homeland_properties=$matches[1]
    [immobile/(.*)] => index.php?homeland_properties=$matches[1] 
    [categoria/(.*)] => index.php?homeland_property_type=$matches[1] 
    [in-affitto] => index.php?homeland_property_status=for-rent 
    [in-vendita] => index.php?homeland_property_status=for-sale 
    [luogo/(.*)] => index.php?homeland_property_location=$matches[1] 
    [attributi/(.*)] => index.php?homeland_property_amenities=$matches[1
    [vendita/([^/]*)] => index.php?pagename=search-property&status=for-sale&type=$matches[1] 
    [vendiamo/(.*)] => index.php?pagename=search-property&status=for-sale&type=$matches[1] 
    ...
    

    ma … ora il mistero si infittisce
    se scrivo le rewrite rule con ‘init’ , così:

    
    add_action( 'init' , function (){
    		add_filter('query_vars', function($qvars){
    			$qvars[] = 'status';
    			$qvars[] = 'type';
    			return $qvars;
    		});
    		add_rewrite_rule( 'vendita/([^/]*)', 'index.php?pagename=search-property&status=for-sale&type=$matches[1]', 'top' ) ;
    		add_rewrite_rule( 'vendiamo/(.*)', 'index.php?pagename=search-property&status=for-sale&type=$matches[1]', 'top' ) ;
    	}) ;
    

    wordpress non le registra

    (ovviamente faccio admin-menu > Settings > Permalink > Save Changes)

    + Comunque come puoi vedere ho attivato anche la regola con il regex
    suggerito da te (cfr sopra: l’ho aggiunta)
    Ma purtroppo, anche con la regola attiva, non ottengo i risultati sperati
    Ovvero se usi il link originale
    https://custaging.caseuniche.it/index.php?pagename=search-property&status=for-sale&type=residenziale
    funziona, ma …
    se usi
    https://custaging.caseuniche.it/vendita/residenziale
    viene riscritto in quello originale ignorando due parametri, ovvero diventa:
    https://custaging.caseuniche.it/index.php?pagename=search-property

    Come vedi non ci sono passi avanti 🙁

    + per conludere questo lungo post: terrò in considerazione il suggerimenti di usare l’url https://custaging.caseuniche.it/cerca/vendita/residenziale

    Comunque non mi perdo d’animo: ci penserò su 🙂

    Grazie per il tempo che mi hai dedicato e per quello che mi dedicherai.
    Se qualcuno ha qualche suggerimento … è il benvenuto 🙂

    Alberto

    Ciao @caseuniche,

    noto un problema nel codice che hai modificato.
    Dovrebbe essere fatto così:

    add_action( 'init' , function () {
    	add_rewrite_rule( 'vendita/([^/]*)', 'index.php?pagename=search-property&status=for-sale&type=$matches[1]', 'top' ) ;
    	add_rewrite_rule( 'vendiamo/(.*)', 'index.php?pagename=search-property&status=for-sale&type=$matches[1]', 'top' ) ;
    });
    
    add_filter( 'query_vars', function($qvars) {
    	$qvars[] = 'status';
    	$qvars[] = 'type';
    	return $qvars;
    });

    In sostanza, add_filter non dovrebbe stare dentro add_action, per questo credo che non stia registrando le regole.

    Prova a correggerlo, aggiornare i Permalink e verificare se cambia qualcosa.
    Ciao!

    Chi ha creato la discussione Alberto

    (@caseuniche)

    Ciao Andrea,
    ho inserito questo codice nel file functions.php del thema child:

    add_filter('query_vars', function($qvars){
    		$qvars[] = 'type';
    		return $qvars;
    	}) ;
    	add_rewrite_rule( 'vendita/([^/]*)', 'index.php?pagename=search-property&status=for-sale&type=$matches[1]', 'top' ) ;
    	
    	add_action ( 'init', function() {	
    		add_filter('query_vars', function($qvars){
    			$qvars[] = 'status';
    			return $qvars;
    		}) ;
    		add_rewrite_rule( 'vendiamo/(.*)', 'index.php?pagename=search-property&status=for-sale&type=$matches[1]', 'top' ) ;
    	});

    in entrambi i casi (dentro o fuori dall’action 'init')
    add_rewrite_rule scrive la regola, ma in posizione deiversa nell’array delle regole (in 15ma posizione e ultima nel codice sotto):

    array ( 'attivita/(.*)' => 'index.php?homeland_properties=$matches[1]', 
    'immobile/(.*)' => 'index.php?homeland_properties=$matches[1]', 
    'servizio/(.*)' => 'index.php?homeland_portfolio=$matches[1]', 
    'lavoro/(.*)' => 'index.php?homeland_portfolio=$matches[1]', 
    'categoria/(.*)' => 'index.php?homeland_property_type=$matches[1]', 
    'in-affitto' => 'index.php?homeland_property_status=for-rent', 
    'in-vendita' => 'index.php?homeland_property_status=for-sale', 
    'luogo/(.*)' => 'index.php?homeland_property_location=$matches[1]', 
    'attributi/(.*)' => 'index.php?homeland_property_amenities=$matches[1]', 
    'servizi' => 'index.php?homeland_portfolio_category=servizi', 
    'per-chi-compra' =>'index.php?homeland_portfolio_category=per-chi-compra', 
    'per-chi-vende' => 'index.php?homeland_portfolio_category=per-chi-vende', 
    'mediazioni' => 'index.php?homeland_portfolio_category=mediazioni', 
    'lavori/(.*)' => 'index.php?homeland_portfolio_category=$matches[1]', 
    'vendita/([^/]*)' => 'index.php?pagename=search-property&status=for-sale&type=$matches[1]', 
    'sitemap_index\\.xml$' => 'index.php?sitemap=1', 
    '([^/]+?)-sitemap([0-9]+)?\\.xml$' => 
    'index.php?sitemap=$matches[1]&sitemap_n=$matches[2]', 
    '([a-z]+)?-?sitemap\\.xsl$' => 'index.php?yoast-sitemap-xsl=$matches[1]', 
    '^wp-json/?$' => 'index.php?rest_route=/', 
    '^wp-json/(.*)?' => 'index.php?rest_route=/$matches[1]', 
    '^index.php/wp-json/?$' => 'index.php?rest_route=/', 
    '^index.php/wp-json/(.*)?' => 'index.php?rest_route=/$matches[1]', 
    '^wp-sitemap\\.xml$' => 'index.php?sitemap=index', '^wp-sitemap\\.xsl$' => 
    'index.php?sitemap-stylesheet=sitemap', '^wp-sitemap-index\\.xsl$' => 
    'index.php?sitemap-stylesheet=index', '^wp-sitemap-([a-z]+?)-([a-z\\d_-]+?)-(\\d+?)\\.xml$' => 
    'index.php?sitemap=$matches[1]&sitemap-subtype=$matches[2]&paged=$matches[3]', 
    '^wp-sitemap-([a-z]+?)-(\\d+?)\\.xml$' => 'index.php?sitemap=$matches[1]&paged=$matches[2]', 
    'property-item/?$' => 'index.php?post_type=homeland_properties', 
    'property-item/feed/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?post_type=homeland_properties&feed=$matches[1]', 
    'property-item/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?post_type=homeland_properties&feed=$matches[1]', 
    'property-item/page/([0-9]{1,})/?$' => 'index.php?post_type=homeland_properties&paged=$matches[1]', 
    'portfolio-item/?$' => 'index.php?post_type=homeland_portfolio', 
    'portfolio-item/feed/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?post_type=homeland_portfolio&feed=$matches[1]', 
    'portfolio-item/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?post_type=homeland_portfolio&feed=$matches[1]', 
    'portfolio-item/page/([0-9]{1,})/?$' => 'index.php?post_type=homeland_portfolio&paged=$matches[1]', 
    'services-item/?$' => 'index.php?post_type=homeland_services', 
    'services-item/feed/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?post_type=homeland_services&feed=$matches[1]', 
    'services-item/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?post_type=homeland_services&feed=$matches[1]', 
    'services-item/page/([0-9]{1,})/?$' => 'index.php?post_type=homeland_services&paged=$matches[1]', 
    'vendiamo/(.*)' => 'index.php?pagename=search-property&status=for-sale&type=$matches[1]', 
    ...

    ma

    in entrambi i casi (dentro o fuori dall’action 'init')
    le query_vars (vedi qui di seguito) non registrano i parametri 'type' e 'status':

    array ( 'page' => 0, 
    'pagename' => 'cu-tools', 
    'error' => '', 
    'm' => '', 
    'p' => 0, 
    'post_parent' => '', 
    'subpost' => '', 
    'subpost_id' => '', 
    'attachment' => '', 
    'attachment_id' => 0, 
    'name' => 'cu-tools', 
    'page_id' => 0, 
    'second' => '', 
    'minute' => '', 
    'hour' => '', 
    'day' => 0, 
    'monthnum' => 0, 
    'year' => 0, 
    'w' => 0, 
    'category_name' => '', 
    'tag' => '', 
    'cat' => '', 
    'tag_id' => '', 
    'author' => '', 
    'author_name' => '', 
    'feed' => '', 
    'tb' => '', 
    'paged' => 0, 
    'meta_key' => '', 
    'meta_value' => '', 
    'preview' => '', 
    's' => '', 
    'sentence' => '', 
    'title' => '', 
    'fields' => '', 
    'menu_order' => '', 
    'embed' => '', 
    'category__in' => array ( ), 
    'category__not_in' => array ( ), 
    'category__and' => array ( ), 
    'post__in' => array ( ), 
    'post__not_in' => array ( ), 
    'post_name__in' => array ( ), 
    'tag__in' => array ( ), 
    'tag__not_in' => array ( ), 
    'tag__and' => array ( ), 
    'tag_slug__in' => array ( ), 
    'tag_slug__and' => array ( ), 
    'post_parent__in' => array ( ), 
    'post_parent__not_in' => array ( ), 
    'author__in' => array ( ), 
    'author__not_in' => array ( ), 
    'post_type' => array ( 0 => 'post', 1 => 'page', 2 => 'e-landing-page', ), 
    'ignore_sticky_posts' => false, 
    'suppress_filters' => false, 
    'cache_results' => true, 
    'update_post_term_cache' => true, 
    'lazy_load_term_meta' => true, 
    'update_post_meta_cache' => true, 
    'posts_per_page' => 30, 
    'nopaging' => false, 
    'comments_per_page' => '50', 
    'no_found_rows' => false, 
    'order' => 'DESC', )

    Ri cordo che gli url
    https://custaging.caseuniche.it/vendita/residenziale/
    https://custaging.caseuniche.it/vendiamo/residenziale/
    vegono regolarmenre ricopiati
    ma nell’url https://custaging.caseuniche.it/?pagename=search-property
    ovvero senza i parametri 'type' e 'status' ( senza la parte &status=for-sale&type=residenziale)

    Quindi direi che il problema sta nella funzione

    add_filter('query_vars', function($qvars){
    		$qvars[] = 'status';
    		$qvars[] = 'type';
    		return $qvars;
    	}) ;

    che non aggiunge i valori in query_vars.

    Ma allora quando è opportuno eseguire questa funzione ?
    E dove inserirla ?

    Se ho inquadrato correttamente il problema 🙁

    Ciao,
    Alberto

    Chi ha creato la discussione Alberto

    (@caseuniche)

    Ciao a tutti

    EUREKA ! trovata la soluzione !

    Mancava un elemento da considerare: il tema per effettuare le ricerche non usa la WP_Query principale creata da wordpress ma ne crea una lui facendo il parsing dei parametri di richiesta direttamente dall’array php $_GET

    La soluzione: ecco il codice (la spiegazione segue):

    
    // ** advanced search slugs
    /*
    add_filter('query_vars', function($qvars){
    	$qvars[] = 'status';
    	$qvars[] = 'type';
    	return $qvars;
    }) ;
    */
    add_rewrite_rule( 'vendita/(.*)', 'index.php?pagename=search-property', 'top' ) ;	
    
    /** 
    *   FIT QUERY VARS TO $_GET ARRAY FOR USING HOMELAND ADVANCED SEARCH
    *   For advanced search some themes (as Homeland) create WP_Query directly from php $_GET array : Homeland theme do that using a filter named 'homeland_advance_search_parameters'.
    *   After apply rewrite rules, WordPress parse request from slug using filter 'query_vars' to define allowed parameters to create main WP_Query 
    * 	
    * 	So with themes using custom WP_Query object, when it rewrites slug, it must to fit to $_GET array correct values from parameters in query string 
    *	
    */
    function  cu_update_get_array_with_url_parts($atts){
    	$trimmed_url = trim(explode('?', $_SERVER['REQUEST_URI'] )[0],'/') ;
    	$url_parts = explode('/', $trimmed_url) ;
    	if( empty($_GET['status']) && !empty($url_parts[0]) ){
    		if('vendita' == $url_parts[0]) $_GET['status'] = 'for-sale' ;
    		if('affitto' == $url_parts[0]) $_GET['status'] = 'for-rent' ;
    	}
    	if(empty($_GET['type'])) $_GET['type'] = $url_parts[1];
    }
    add_filter( 'homeland_advance_search_parameters','cu_update_get_array_with_url_parts', 8);
    

    Ed ecco la spiegazione (come da breve nota nei commenti del codice)

    + poichè il tema usa una WP_query custom l’uso del filtro 'query_vars' diventa inutile, visto che filtra i parametri permessi solo per la query standar di wordpress. Per questo motivo il codice ralativo è stato rimosso

    /*
    add_filter('query_vars', function($qvars){
    	$qvars[] = 'status';
    	$qvars[] = 'type';
    	return $qvars;
    }) ;
    */

    + visto che i parametri per la WP_query custom vengono letti dal tema direttamente da$_GET (ovvero dalla url originale prima del rewrite)
    non è necessario trascriverli nella regola rewrite, quindi sono stati eliminati
    add_rewrite_rule( 'vendita/(.*)', 'index.php?pagename=search-property', 'top' )

    + visto che i parametri per la WP_query custom vengono letti dal tema direttamente da$_GET (ovvero dalla url originale prima del rewrite)
    bisogna assicurarsi che siano in $_GET prima del parsing da parte del tema.
    Ma nella nostra url originale i parametri non ci sono !
    Fortunatamente il tema mette a disposizione un filtro (che usa proprio per il parsing di $_GET) chiamato 'homeland_advance_search_parameters'
    che possiamo utilizzare per scrivere in $_GET i parametri che ci interessano

    function  cu_update_get_array_with_url_parts($atts){
    		$trimmed_url = trim(explode('?', $_SERVER['REQUEST_URI'] )[0],'/') ;
    		$url_parts = explode('/', $trimmed_url) ;
    		if( empty($_GET['status']) && !empty($url_parts[0]) ){
    			if('vendita' == $url_parts[0]) $_GET['status'] = 'for-sale' ;
    			if('affitto' == $url_parts[0]) $_GET['status'] = 'for-rent' ;
    		}
    		if(empty($_GET['type'])) $_GET['type'] = $url_parts[1];
    	}
    	add_filter( 'homeland_advance_search_parameters','cu_update_get_array_with_url_parts', 8);

    NOTA: il filtro viene aggiunto con precedenza 8 per assicurarsi che venga eseguito prima che il tema faccia il parsing.

    Ecco tutto.

    Spero che le soluzioni trovate servano o ispirino altri per risolvere i loro problemi.
    Un ringraziamento particolare ad Anrea Porotti che si è dedicato al mio problema.

    Ciao a tutti,
    Alberto

Stai visualizzando 15 risposte - dal 1 al 15 (di 15 totali)
  • Il topic ‘add_rewrite_rule per pagina e campi’ è chiuso a nuove risposte.