Récupère l'URL de la page actuelle (y compris la pagination)
8 réponses
- votes
-
- 2013-12-15
Enplus de la réponse de Rajeev Vyas,vousn'avezpasbesoin depasser deparamètresnon vides à
add_query_arg()
. Ce qui suit atoujoursbien fonctionnépourmoi:// relative current URI: $current_rel_uri = add_query_arg( NULL, NULL ); // absolute current URI (on single site): $current_uri = home_url( add_query_arg( NULL, NULL ) );
Lafonction se replie sur
$_SERVER[ 'REQUEST_URI' ]
et lui appliqueurlencode_deep()
. Voir https://github.com/WordPress/WordPress/blob/3.8/wp-includes/functions.php # L673Modifier: Comme
$_SERVER[ 'REQUEST_URI' ]
représente uneentrée utilisateurnonfiltrée,ilfauttoujours échapper à la valeur de retour deadd_query_arg()
lorsque le contexteestmodifié. Parexemple,utilisezesc_url_raw()
pour l'utilisation de labase de données ouesc_attr()
ouesc_url()
pour le HTML.<❯Mise àjour
L'exemplemontré qui devrait créer un URI absolu (contenant le schémaet l'hôte)ne fonctionnepas sur lemultisite avec des sous-répertoires car
home_url()
renverrait l'URI complet comprenant un segment de chemin. Unemeilleure solutionpour le code compatiblemultisite serait la suivante:// absolute URI in multisite aware environment $parts = parse_url( home_url() ); $current_uri = "{$parts['scheme']}://{$parts['host']}" . add_query_arg( NULL, NULL );
Le cœur de WordPressne prendpasen charge leport,l'utilisateur ou lemot depasse dans une URL de sitemultisite,cela devrait donc être suffisant.
In addition to Rajeev Vyas's answer, you don't need to pass any non-empty parameters to
add_query_arg()
. The following has always worked well for me:// relative current URI: $current_rel_uri = add_query_arg( NULL, NULL ); // absolute current URI (on single site): $current_uri = home_url( add_query_arg( NULL, NULL ) );
The function falls back on
$_SERVER[ 'REQUEST_URI' ]
and appliesurlencode_deep()
to it. See https://github.com/WordPress/WordPress/blob/3.8/wp-includes/functions.php#L673Edit: As
$_SERVER[ 'REQUEST_URI' ]
represents unfiltered user input, one should always escape the return value ofadd_query_arg()
when the context is changed. For example, useesc_url_raw()
for DB usage oresc_attr()
oresc_url()
for HTML.Update
The shown example that should create an absolute URI (containing scheme and host) does not work on multisite with sub-directories as
home_url()
would return the complete URI including a path segment. A better solution for multisite aware code would be this:// absolute URI in multisite aware environment $parts = parse_url( home_url() ); $current_uri = "{$parts['scheme']}://{$parts['host']}" . add_query_arg( NULL, NULL );
WordPress core does not support port, user or password in a multisite site URL so this should be sufficient.
-
Frustrant qu'OPn'aitpas choisi cette réponse comme solution,ce qu'elleest.Je vous remercie.Frustrating that OP did not select this answer as the Solution, which it is. Thank you.
- 0
- 2019-08-09
- cfx
-
- 2013-02-01
global $wp; $current_url = add_query_arg( $wp->query_string, '', home_url( $wp->request ) );
Pas unefonction,mais certainementen utilisant du code wordpress ..
global $wp; $current_url = add_query_arg( $wp->query_string, '', home_url( $wp->request ) );
Not a function, but definately using wordpress code..
-
Celafonctionneen partie,mais certaines chosesne fonctionnentpas commeje le souhaite: desparamètrestels que `year` sont ajoutés à la chaîne de requête,même s'ilsn'y ontjamais été auparavant,et d'autresparamètres,parexemple leparamètre` replytocom`,Foutez le camp.Connaissez-vous une solutionpour cela?It works partly, but some things don't work like I want them: Parameters like `year` are added to the query string, even though they haven't been there before, and other parameters, for example the `replytocom` parameter, get lost. Do you know a solution for this?
- 2
- 2013-02-01
- René Schubert
-
- 2013-03-11
wp_guess_url est ce que vous recherchez.
Devinez l'URL du site.
Supprimera les liens wp-adminpour récupérer uniquement les URL de retourne figurantpas dans le répertoire wp-admin.
wp_guess_url is what you are looking for.
Guess the URL for the site.
Will remove wp-admin links to retrieve only return URLs not in the wp-admin directory.
-
Cela renvoie une URLtotalement différente de lapage actuelle lorsquej'aiessayé de l'utiliser.This returns a totally different URL other than the current page when I tried using it.
- 0
- 2015-05-19
- Kirby
-
- 2014-02-02
1)
$ _SERVER ['REQUEST_URI']
- Il renvoie l'URLpour accéder à lapage quiexécute le script. Si vous deveztaperhttp://www.example.com/product.php?id=5
pour accéder à lapage,$ _SERVER ['REQUEST_URI']
renvoie < code>/product.php?id=5 .2)
$ _SERVER ['DOCUMENT_ROOT']
- Retourne le répertoire racine du serveur quiest spécifié dans lefichier de configuration du serveur. Cette variable renvoiegénéralement le chemin comme/usr/yoursite/www
sous LinuxetD:/xamps/xampp/htdocs
sous Windows.3)
$ _SERVER ['HTTP_HOST']
- Renvoie lenom de l'hôtetel qu'il setrouve dans l'en-tête http. Cette variable renvoiegénéralement le chemin commeexample.com
lorsque voustrouvezhttp://example.com
dans labarre d'adresse dunavigateuret renvoyezwww.example.com
lorsque vous voyezhttp://www.example.com
dans labarre d'adresse. Ceciesttrès utile lorsque vous devez conserver la sessionen effectuant unpaiementen ligneen utilisant PHP car la session stockéepourhttp://example.com
n'estpas lamême quepourhttp://www.example.com
.4)
$ _SERVER ['HTTP_USER_AGENT']
- Renvoie les détails de l'agent utilisateur (navigateur) accédant à lapage Web. Nouspouvons utiliserstrpos ($ _ SERVER ["HTTP_USER_AGENT"],"MSIE")
pour détecter Microsoft Internet Explorer ou vouspouvez utiliserstrpos ($ _ SERVER ["HTTP_USER_AGENT"],"Firefox")
pour détecter lenavigateur Firefoxen PHP.5)
$ _SERVER ['PHP_SELF']
- Renvoie lenom defichier du scripten cours d'exécution. Supposons que vous accédiez à l'URLhttp://www.example.com/product.php?id=5
puis$ _SERVER ['PHP_SELF']
renvoie < code>/product.php dans votre script.6)
$ _SERVER ['QUERY_STRING']
- Renvoie la chaîne de requête si la chaîne de requêteest utiliséepour accéder au scripten cours d'exécution. Les chaînes de requête sont celles qui sont disponibles après "?" sign.si vous utilisez$ _SERVER ['QUERY_STRING']
dans le scriptexécutant l'URL suivantehttp://www.example.com/index.php?id=5&page=product
puisil renvoieid=5 & amp;page=product
dans votre script.7)
$ _SERVER ['REMOTE_ADDR']
- Renvoie l'adresse IP de lamachine distante accédant à lapageen cours. Mais vousne pouvezpas vous reposer sur$ _SERVER ['REMOTE_ADDR']
pour obtenir la véritable adresse IP de lamachine du client. Consultez cet articlepour savoir comment obtenir de véritables addrees IPen PHP.8)
$ _SERVER ['SCRIPT_FILENAME']
- Renvoie le chemin absolu dufichieren cours d'exécution. Il renvoie un chemin commevar/example.com/www/product.php
sous Linuxet un chemin commeD:/xampp/xampp/htdocs/test/example.php
dans Windows .1)
$_SERVER['REQUEST_URI']
- It return the URL in to access the page which is executing the script. If you need to typehttp://www.example.com/product.php?id=5
to access the page then$_SERVER['REQUEST_URI']
returns/product.php?id=5
.2)
$_SERVER['DOCUMENT_ROOT']
– Returns the root directory of the server which is specified in the configuration file of server. This variable usually returns the path like/usr/yoursite/www
in Linux andD:/xamps/xampp/htdocs
in windows.3)
$_SERVER['HTTP_HOST']
– Returns the host’s name as found in the http header. This variable usually returns the path likeexample.com
when the you findhttp://example.com
in browser’s address-bar and returnwww.example.com
when you seehttp://www.example.com
in the address-bar. This is quite useful when you’ve to preserve session while making online payment using PHP since session stored forhttp://example.com
is not same as for thehttp://www.example.com
.4)
$_SERVER['HTTP_USER_AGENT']
- Returns the user agent’s (browser) detail accessing the web page. We can usestrpos($_SERVER["HTTP_USER_AGENT"],”MSIE”)
to detect Microsoft Internet explorer or you can usestrpos($_SERVER["HTTP_USER_AGENT"],”Firefox”)
to detect firefox browser in PHP.5)
$_SERVER['PHP_SELF']
- Returns the file-name of the currently executing script. Let’s suppose that you’re accessing the URLhttp://www.example.com/product.php?id=5
then$_SERVER['PHP_SELF']
returns/product.php
in your script.6)
$_SERVER['QUERY_STRING']
– Returns the query string if query string is used to access the script currently executing. Query strings are those string which is available after “?” sign.if you use$_SERVER['QUERY_STRING']
in the script executing the following URLhttp://www.example.com/index.php?id=5&page=product
then it returnsid=5&page=product
in your script.7)
$_SERVER['REMOTE_ADDR']
– Returns the IP address of remote machine accessing the current page. But you can’t relie on$_SERVER['REMOTE_ADDR']
to get the real IP address of client’s machine. See this article to know how to get real IP addrees in PHP.8 )
$_SERVER['SCRIPT_FILENAME']
- Returns the absolute path of the file which is currently executing. It returns path likevar/example.com/www/product.php
in Linux and path likeD:/xampp/xampp/htdocs/test/example.php
in windows.-
Gardez à l'esprit qu'aucun de ceux-cin'est disponible dans votre CLIet doncinutilepour lestâches cron.Keep in mind that none of those are available in your CLI and therefore useless for cron jobs.
- 1
- 2014-02-26
- kaiser
-
- 2016-08-29
add_query_args( null, null )
créera un élément detableau avec une clé vide ($qs[""] = null
)bien qu'iln'affecterapas le résultat.
Selon add_query_arg ()| Fonction| Ressourcespour les développeurs WordPress , les 2ème,3èmeparamètres sontfacultatifset peuvent être omis.
add_query_args( null, null )
peut être plus court .$current_url = add_query_args( [] );
Ilexiste également la version laplus courte ,bien qu'ellene soitpas recommandée car lepremierparamètreest leparamètre obligatoire.
$current_url = add_query_args();
Deplus,notez que
home_url( add_query_vars( [] ) )
ethome_url( add_query_arg( null, null ) )
peuventne pas renvoyer l'URL réelle lorsque WordPressestinstallé dans un sous-répertoire.parexemple
https://example.com/wp/wp/foo
peut être renvoyé lorsque WordPressestinstallé danshttps://example.com/wp/
.
Mise àjour: 23/01/2017
Ma versionbasée sur la solution de Davidpour obtenir une URL absolue.
$parts = parse_url(home_url()); $uri = $parts['scheme'] . '://' . $parts['host']; if (array_key_exists('port', $parts)) { $uri .= ':' . $parts['port']; } $uri .= add_query_arg([]);
add_query_args( null, null )
will create an array element with empty key ($qs[""] = null
) although it won't affect the result.
According to add_query_arg() | Function | WordPress Developer Resources, the 2nd, 3rd parameters are optional and they can be omitted.
add_query_args( null, null )
can be more shorter.$current_url = add_query_args( [] );
There is also the shortest version although it isn't recommended as the 1st parameter is the required parameter.
$current_url = add_query_args();
In addition, note that both
home_url( add_query_vars( [] ) )
andhome_url( add_query_arg( null, null ) )
might not return actual URL when WordPress is installed in a sub-directory.e.g.
https://example.com/wp/wp/foo
might be returned when WordPress is installed inhttps://example.com/wp/
.
Update: 2017/01/23
My version based on the David's solution to get absolute URL.
$parts = parse_url(home_url()); $uri = $parts['scheme'] . '://' . $parts['host']; if (array_key_exists('port', $parts)) { $uri .= ':' . $parts['port']; } $uri .= add_query_arg([]);
-
- 2017-02-06
Pourmoi
<?php esc_url(the_permalink()); ?>
fonctionne (sur unepage d'archive avecpagination).For me
<?php esc_url(the_permalink()); ?>
works (on a archive page with pagination).-
Impossible.`the_permalink ()`fait écho aupermalien échappé,ilne renvoie rien.Le `esc_url ()`n'obtient rien,et si c'était le cas,ce serait une URL échappée.Impossible. `the_permalink()` echoes the escaped permalink, it doesn't return anything. The `esc_url()` doesn't get anything, and if it would, it would be an escaped URL.
- 0
- 2017-02-06
- fuxia
-
Vous avez raison,celan'afonctionné quegrâce à lamiseen cachepermalien,je pense.You're right, it worked only because of permalink caching I think.
- 0
- 2017-02-06
- Henning Fischer
-
- 2013-02-01
Jen'aiplus depagination mais Vouspouvez utiliser cettefonctionpour obtenir l'URL dans laboucle
<?php $ID = get_the_ID(); echo get_permalink( $ID ); ?>
Oubien si vousne préférezpas utiliserphp,vouspouvez également opterpour laméthodejqueryici (cela vous aidera à lefairefonctionneren dehors de laboucle)
$(document).ready(function () { var vhref = $(location).attr('href'); var vTitle = $(this).attr('title'); $('#spnTitle').html('' + vTitle + ''); $('#spnURL').html('' + vhref + ''); });
ou si vouspréférez utiliser lafonctionphp,vous devez obtenir l'identifianten dehors de laboucle
I dont now of pagination but You can use this function to get url within the loop
<?php $ID = get_the_ID(); echo get_permalink( $ID ); ?>
Or else if you dont prefer to use php you can also opt for jquery method here (this will help you to make it work outside the loop)
$(document).ready(function () { var vhref = $(location).attr('href'); var vTitle = $(this).attr('title'); $('#spnTitle').html('' + vTitle + ''); $('#spnURL').html('' + vhref + ''); });
or if u prefer to use php function you need to get the id outside the loop
-
Désolé,mais cen'esttout simplementpas ce quej'ai demandé ... + `the_permalink ()`n'apasbesoin de l'identifiant quandilest appelé dans laboucle.Sorry, but this is just not what I've asked for... + `the_permalink()` doesn't need the id when it's called inside the loop.
- 1
- 2013-02-01
- René Schubert
-
Cette réponsen'avait quetrèspeu à voir avec la questioninitiale.Iln'y apas répondu correctementet n'apas vraiment donné d'informationsprécieuses sur le sujet.This answer had very little to do with the original question. It didn't answer it correctly nor did it really give any valuable information concerning the topic.
- 2
- 2013-07-04
- jounileander
-
- 2014-02-26
Vouspouvez utiliser lafonction wordpresspour obtenir l'URL de lapage actuelle
the_permalink()
Cela vous renverra le lien URL de lapage actuelle.
You can use wordpress function to get current page URL
the_permalink()
This will return you the curremt page URL link.
-
Presque;`the_permalink ()` affichera * l'URL dumessage actuel.Mais celane fonctionnerapaspour les autres requêteset n'inclurapas de variables comme lapagination.Doncpas vraiment la réponse que @ René Schubert recherche.Almost; `the_permalink()` will *print* the URL of the current post. But it won't work for other requests, and won't include variables like pagination. So not really the answer @René Schubert is looking for.
- 4
- 2014-02-26
- TheDeadMedic
Existe-t-il unefonction WPpour obtenir automatiquement l'URL correcte de lapage actuelle? Cela signifie que sije viens d'ouvrir un seul article,lafonction renvoie lamême chose que
get_permalink()
,mais sije suis sur uneinstancepaginée d'unepage (lors de lapagination àtravers les commentaires),lafonction renvoie lecomme leferaitget_pagenum_link(get_query_var('paged'))
.J'ai cherché dans le codexmaisje n'aipastrouvé ce queje cherchais.(Maismême
get_pagenum_link()
n'yestpas documenté.)Je connais déjà cettefonction ,maisje serais heureux s'il y avait unefonction WP "native" qui lefasseletravail.
Merci d'avance!Cordialement,René