Deseja exibir o endereço IP de um usuário no WordPress?
Se os usuários precisarem saber o endereço IP para configurar um de seus produtos ou concluir um tutorial, será útil mostrar a eles o endereço IP exato que precisam usar.
Neste artigo, mostraremos como exibir o endereço IP de um usuário no seu site WordPress.
Por que exibir o endereço IP de um usuário no WordPress?
Um endereço IP (Internet Protocol) é uma sequência de números separados por pontos que é usada para identificar dispositivos de hardware em uma rede. Isso significa que o endereço IP do visitante simplesmente identifica o dispositivo que ele está usando para se conectar à Internet, como seu smartphone, computador ou tablet.
Há muitos casos em que os visitantes podem precisar saber seu endereço IP. Por exemplo, às vezes os usuários precisam digitar seu endereço IP exclusivo ao configurar um software, especialmente plug-ins de segurança do WordPress, como firewalls.
Se você vende esse tipo de software, mostrar o endereço IP exclusivo do usuário em sua documentação on-line ajudará seus clientes a configurar o novo software.
Mesmo que você não venda o software, muitos blogueiros do WordPress publicam guias úteis sobre como usar software de terceiros. Se você estiver escrevendo um tutorial em que o leitor precisa digitar o endereço IP, mostrar o endereço IP exato que ele precisa usar pode ajudá-lo a criar um tutorial muito melhor.
Nesta postagem, apresentamos várias maneiras de mostrar o endereço IP do usuário em seu site WordPress. Se você preferir ir direto para um método específico, poderá usar os links abaixo.
- Como exibir o endereço IP de um visitante no WordPress usando um plug-in
- Como exibir o endereço IP de um visitante no WordPress usando código
1. Como exibir o endereço IP de um visitante no WordPress usando um plug-in
A maneira mais fácil de exibir o endereço IP de um usuário no WordPress é usar o plug-in User IP and Location. Esse é um plug-in simples que permite mostrar o endereço IP do visitante em qualquer página, post ou área pronta para widget usando um shortcode.
Primeiro, você precisará instalar e ativar o plug-in. Se precisar de ajuda, consulte nosso guia sobre como instalar um plug-in do WordPress.
Após a ativação, basta abrir a página, o post ou a área pronta para widget em que você deseja mostrar o endereço IP do visitante. Em seguida, clique no ícone de bloco de adição “Mais” e procure por “Shortcode”.
Quando o bloco correto for exibido, clique para adicioná-lo ao seu site WordPress.
Agora, basta digitar o shortcode [userip_location type=ip]. Para obter uma visão mais detalhada sobre o uso de códigos de acesso, consulte nosso guia para iniciantes sobre como adicionar um código de acesso no WordPress.
Depois de fazer isso, clique no botão “Update” (Atualizar) ou “Publish” (Publicar) para salvar suas alterações.
Agora, se você visitar essa página, verá seu endereço IP exclusivo.
2. Como exibir o endereço IP de um usuário no WordPress usando código
Você também pode mostrar o endereço IP de um usuário adicionando um código ao seu blog ou site do WordPress. Esse código criará um shortcode exclusivo que poderá ser colocado em qualquer lugar do site.
Isso é tão simples quanto copiar e colar algum código em seu site. No entanto, é sempre uma boa ideia criar um backup antes de fazer alterações no código de seu site.
Se ainda não estiver fazendo o backup do seu site WordPress, consulte nossa seleção de especialistas dos melhores plug-ins de backup do WordPress.
Para mostrar o endereço IP do usuário, abra o arquivo functions.php do seu tema, crie um plug-in específico do site ou use um plug-in de trechos de código.
Independentemente da opção escolhida, você pode simplesmente colar o seguinte código:
function get_the_user_ip() {
if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
//check ip from share internet
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
//to check ip is pass from proxy
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return apply_filters( 'wpb_get_ip', $ip );
}
add_shortcode('show_ip', 'get_the_user_ip');
Depois de fazer isso, ative o plug-in específico do site, salve o snippet de código ou salve as alterações feitas no arquivo functions.php do site.
Agora você criou um shortcode [show_ip] que pode ser usado para mostrar o endereço IP do visitante em qualquer página, post ou área pronta para widget.
Para obter um guia passo a passo sobre como colocar o shortcode, consulte nosso guia para iniciantes sobre como adicionar um shortcode no WordPress.
Esperamos que este artigo o tenha ajudado a aprender como exibir o endereço IP de um usuário em seu site WordPress. Talvez você também queira conferir nosso guia sobre como permitir o registro de usuários no seu site WordPress e o melhor software de bate-papo ao vivo para pequenas empresas.
Se você gostou deste artigo, inscreva-se em nosso canal do YouTube para receber tutoriais em vídeo sobre o WordPress. Você também pode nos encontrar no Twitter e no Facebook.
Syed Balkhi says
Hey WPBeginner readers,
Did you know you can win exciting prizes by commenting on WPBeginner?
Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
You can get more details about the contest from here.
Start sharing your thoughts below to stand a chance to win!
Christopher says
Great article! Is it also possible to show visitors country?
WPBeginner Support says
That would require some advanced php or a plugin, we don’t have a recommended method at the moment.
Administrador
Lathif says
unfortunately there is still a weakness of the function, that is the problem of “cache”.
visitors will see the same ip address (even if the router is restarted) when they are not clearing “cache” in the browser.
Pamela says
Is there a way to display the user’s country flag with this code?
Thanks.
Lloyd says
How about a city or state instead of IP?
Beatriz says
Where can I see the IP’s collected? and should I paste the snippet of the code on the top of my function.php code?
WPBeginner Support says
Paste the code at the bottom of your functions.php file. You will have to use shortcode
[show_ip]
inside a text widget. See our guide on how to add and use widgets in WordPress.Administrador
Brigitte Scherieble says
hey,
I am from Germany and I am not a computer freak. But I have the job to find out of the client IP (out of Google Analytics) the Company of the visiter. Can you help me?
Evan says
This works great, thank you! Is there any way to have it also display the hostname, perhaps with a separate shortcode?
Reuben Tinto says
Hi,
Is it possible to obtain the IP of a previous blog visitor trough this method? If not are you aware of any other courses of action I can take?
Also will I be able to access code if I do not have a premium wordpress account?
I have been trying to locate the IP of an anonymous twitter troll and would really appreciate some help!
Reuben
Mike says
Thanks for the tutorial. Please excuse if this is a dumb question but I’m new to working with WordPress.
If I want to store the visitors IP address along with the date and time they visited a post, should I create a separate mysql database table or is there an existing wp table that collects this information that I can retrieve?
WPBeginner Support says
WordPress only stores vistor’s information in the database if they decide to leave a comment. You can create a separate database to collect this information if you want.
Administrador
Mohammad Mursaleen says
Creating a table for such functionality in WordPress is not an efficient move. I would prefer to do this using custom post type.
I have answered a similar question over here;
Vivek Digarse says
Thanks !
John says
Thanks for this, works fine.
But is it possible to use this to monitor new user subscriptions?
alexander kochubey says
Thanks for reply, I’ll modify some plugin for some system, I’ll describe it later
meera says
HI
Thank you so much…. it works fine……..
Abhisek Padhi says
@pippin you are correct. Your code worked fine, but wpbeginner’s code was also working fine.
Doug Hall says
Display it where? I don’t understand the post at all.
as says
Everywhere use shortcode [show_ip]
Pippin Williamson says
It should probably be noted that $_SERVER[‘REMOTE_ADDR’] will not always retrieve the IP properly.
If the user is on a shared connection, you will need to use $_SERVER[‘HTTP_X_FORWARDED_FOR’].
If the user is behind a proxy, you will need to use $_SERVER[‘HTTP_X_FORWARDED_FOR’].
The IP can also be present in $_SERVER[‘HTTP_CLIENT_IP’].
To properly get the IP reliably, something like this should be used:
function get_the_user_ip() {
if ( ! empty( $_SERVER[‘HTTP_CLIENT_IP’] ) ) {
//check ip from share internet
$ip = $_SERVER[‘HTTP_CLIENT_IP’];
} elseif ( ! empty( $_SERVER[‘HTTP_X_FORWARDED_FOR’] ) ) {
//to check ip is pass from proxy
$ip = $_SERVER[‘HTTP_X_FORWARDED_FOR’];
} else {
$ip = $_SERVER[‘REMOTE_ADDR’];
}
return apply_filters( ‘edd_get_ip’, $ip );
}
Pippin Williamson says
Formatted version: https://gist.github.com/pippinsplugins/9641841
WPBeginner Support says
Thanks Pippin, we have updated the article.
Administrador
Chris Black says
Always worth noting that although you can read the IP address with PHP that it may not be useful because people have shared IP addresses, dynamic IP, access websites from different networks/locations and because it is possible to fake the IP address that PHP sees. So – only use an IP address with caution.