Sempre postamos tutoriais que envolvem adicionar trechos de código (snippets) ao arquivo functions.php do seu tema WordPress. Embora este processo seja bastante fácil para aqueles que sabem como o PHP funciona, parece um pouco complicado para os iniciantes. Muitas vezes, novos usuários querem realizar o resultado final do tutorial, mas falta-lhes o conhecimento de PHP para entender como colar o código corretamente, sem prejudicar o site. Não há nada de errado com isso, e se você está lendo este artigo, provavelmente prejudicou o seu site fazendo isso. Antes, queremos assegurar-lhe de que você não é o único. Todos nós, quando começamos cometemos esse erro. Neste artigo, vamos mostrar a você como evitar os erros mais comuns, quando for colar o código PHP de tutoriais no arquivo functions.php do seu tema WordPress.
[nota]O arquivo functions.php do tema, geralmente, está localizado na pasta /wp-content/themes/seutema/. Este arquivo NÃO é o mesmo que o arquivo functions.php (core do WordPress) localizado no diretório /wp-includes/.[/nota]
ATUALIZAÇÃO IMPORTANTE:
Recomendamos ultimamente, que você crie um Plugin Específico do Site para colar seus Snippets. Clique no link para saber mais sobre isso.
Para entender como colar o código corretamente, você precisa entender a semântica básicos do PHP.
//Esta é a tag de abertura de um código PHP <?php //Esta é a tag de fechamento de um código PHP ?>
A razão pela qual você precisa para se familiarizar com isso é porque mais de 95% dos problemas que temos corrigido, envolve problemas de colar o código em um lugar errado. Então, saber a semântica do PHP é muito útil. Abaixo estão alguns dos erros mais comuns que vemos:
1° Erro Mais Comum
O usuário encontra um código PHP no site, como abaixo, e cola-o no lugar errado.
<?php add_filter( 'login_headerurl', 'custom_loginlogo_url' ); function custom_loginlogo_url($url) { return 'https://wp24horas.com.br'; } ?>
Código do arquivo functions.php do tema Exemplo (Nota: Geralmente o arquivo functions.php do tema tem muito mais código, mas a ideia é a mesma):
<?php //Toneladas de código PHP que já existe aqui no seu arquivo //O Usuário deve copiar e colar o snippet que encontraram na web como este: <?php add_filter( 'login_headerurl', 'custom_loginlogo_url' ); function custom_loginlogo_url($url) { return 'https://wp24horas.com.br'; } ?> ?>
Obviamente, isso vai pirar o WordPress, porque você tem uma nova tag de abertura PHP sem fechar a tag PHP existente. Há duas maneiras de corrigir esse problema. O primeiro método é colar o item no lugar certo:
<?php //Toneladas de código PHP que já existe aqui no seu arquivo //Veja como fechamos corretamente a primeira tag PHP ?> //Agora nos podemos abrir outra tag PHP. <?php add_filter( 'login_headerurl', 'custom_loginlogo_url' ); function custom_loginlogo_url($url) { return 'http://www.wpbeginner.com'; } ?>
Observe, como nós colamos corretamente o código PHP depois que a tag PHP anterior foi fechada.
Outro método é simplesmente retirar a tag de abertura e fechamento de sua nova função WordPress. Assim, o exemplo ficaria assim:
<?php //Toneladas de código PHP que já existe aqui no seu arquivo // Novo código só vai aqui (Observe como nós retiradmos as tags de abertura e fechamento do PHP do novo código) add_filter( 'login_headerurl', 'custom_loginlogo_url' ); function custom_loginlogo_url($url) { return 'https://wp24horas.com.br'; } ?>
2° Erro Mais Comum
Cada autor de tutorial tem seu próprio estilo de escrever. Alguns mantêm seus snippets dentro das tags PHP como você viu no exemplo acima. Outros autores não envolvem seus snippets com tags PHP.
Isso nos leva ao segundo problema. Se você tem um código como este:
function custom_loginlogo() { echo '<style type="text/css"> h1 a {background-image: url('.get_bloginfo('template_directory').'/images/login_logo.png) !important; } </style>'; } add_action('login_head', 'custom_loginlogo');
O autor está supondo que você sabe que este código deve ir dentro das tags PHP. Alguns até sugerem que você coloque o seu código na parte inferior do arquivo functions.php do seu tema. O exemplo de um erro de iniciante é:
<?php //Toneladas de código PHP que já existe aqui no seu arquivo ?> //Em seguida, o usuário cola o código aqui (Observe que a tag PHP já está fechados acima): function custom_loginlogo() { echo '<style type="text/css"> h1 a {background-image: url('.get_bloginfo('template_directory').'/images/login_logo.png) !important; } </style>'; } add_action('login_head', 'custom_loginlogo');
Note que o usuário colou o código fora das tags PHP. O WordPress não sabe qual é o código, assim, vai parar.
Um código correto seria algo como isto:
<?php //Toneladas de código PHP que já existe aqui no seu arquivo //O novo vai aqui function custom_loginlogo() { echo '<style type="text/css"> h1 a {background-image: url('.get_bloginfo('template_directory').'/images/login_logo.png) !important; } </style>'; } add_action('login_head', 'custom_loginlogo'); //PHP End Tag ?>
3° Erro Mais Comum
Agora que nós falamos sobre a questão de abertura e fechamento das tags PHP, o último erro mais comum que vemos, envolve usuário colando novos snippets dentro de uma função existente.
A anatomia de uma função geralmente se parece com isso:
function custom_function_name() { // Esta é a tag de abertura da função<br /><br />//O código especifico para a função vai aqui<br /><br />} // Esta é a tag de fechamento da função
Se você colar uma outra função dentro de uma função, então ele fará com que seu site pare. Um exemplo deste erro seria algo como:
function custom_function_name() { // Esta é a tag de abertura da função // O código específico para a função vai aqui function custom_loginlogo() { echo '<style type="text/css"> h1 a {background-image: url('.get_bloginfo('template_directory').'/images/login_logo.png) !important; } </style>'; } add_action('login_head', 'custom_loginlogo'); } // Esta é a tag de fechamento da função
Você não pode fazer isso. Cada função é independente, então, você não pode colocar as duas juntas. A maneira correta de colar seria assim:
function custom_function_name() { // Está é a tag de abertura da função // o código específico da função vai aqui } // Esta é a tag de fechamento da função function custom_loginlogo() { echo '<style type="text/css"> h1 a {background-image: url('.get_bloginfo('template_directory').'/images/login_logo.png) !important; } </style>'; } add_action('login_head', 'custom_loginlogo');
Os 3 erros comuns acima, provavelmente, são a razão pela qual o seu tema deixou de funcionar, quando você copiou e colou um snippet da web no arquivo functions.php do seu tema WordPress
Outras dicas úteis
Há momentos em que nós rodamos snippets apenas para descobrir que o código colado tinha erros. Alguns realmente, são erros descuidados, como o desenvolvedor não colocar “;” ou fechar uma citação. Outros eram erros funcionais, com o próprio código ou o usuário não seguindo as instruções corretamente.
É fundamental que você tenha o plugin ativado se ele estiver sendo usado no tutorial. Alguns autores de tutorial apenas chamam a função do plugin, diretamente em seu snippet sem ter a instrução condicional para verificar se o plugin existe. Você pode culpar tanto o usuário quanto o autor por isso. O autor deveria ter inserido a instrução condicional no lugar certo, mas o usuário também deveria ter lido o artigo de forma adequada e instalado o plugin necessário.
Há momentos em que você encontra snippets longos, que você realmente deseja. Por exemplo, nosso snippet do Gravity Forms. Alguns autores têm a tendência de explicar o código para seus usuários (o que é uma coisa boa), mas também faz com que haja erros no código. Então, uma coisa que nós fazemos é rolar para baixo ou para cima para tirar o snippet de código final, ao invés de juntar as peças por nós mesmos.
Deparou-se com esses erros? Como você lidou com eles? Você encontrou um problema que nós não mencionamos acima? Se sim, por favor, compartilhe conosco nos comentários.
108 respostas
Thanks for your personal marvelous posting! I genuinely enjoyed reading it, you’re a great author.
I will be sure to bookmark your blog and will often come back in the foreseeable future.
I want to encourage yourself to continue your great job, have a nice afternoon!
I don’t know if it’s just me or if perhaps everybody
else encountering issues with your blog. It appears as
though some of the written text in your posts are running off the
screen. Can somebody else please comment and let me know if this is happening to them too?
This could be a issue with my web browser because I’ve had this happen previously.
Many thanks
I am sure this article has touched all the internet people,
its really really fastidious piece of writing on building up
new blog.
Incredible! This blog looks just like my old one! It’s on a totally different
subject but it has pretty much the same layout and design. Wonderful choice of colors!
Very rapidly this web page will be famous amid all
blogging visitors, due to it’s fastidious articles
Whats up very nice site!! Guy .. Beautiful .. Amazing ..
I’ll bookmark your website and take the feeds additionally?
I am happy to search out numerous useful info right here within the put up, we want
develop more techniques in this regard, thank you for sharing.
. . . . .
Nice post. I used to be checking continuously this blog and
I’m inspired! Extremely helpful info particularly the final part 🙂 I handle such info a lot.
I was seeking this particular information for a long time.
Thank you and best of luck.
I really like what you guys are up too. This sort of clever work and reporting!
Keep up the excellent works guys I’ve included you guys to
our blogroll.
You can definitely see your expertise in the article you write.
The world hopes for more passionate writers like you who
aren’t afraid to mention how they believe. Always go after your heart.
Nice replies in return of this difficulty with solid arguments and explaining all regarding that.
Greetings, There’s no doubt that your website could be having web browser compatibility problems.
Whenever I take a look at your blog in Safari, it looks fine however
when opening in I.E., it’s got some overlapping
issues. I just wanted to provide you with a quick heads up!
Besides that, wonderful site!
Magnificent beat ! I would like to apprentice even as you amend your site,
how can i subscribe for a blog site? The account aided me a acceptable deal.
I had been tiny bit familiar of this your broadcast provided vivid clear idea
Can I simply just say what a comfort to uncover a person that truly
knows what they are talking about online. You definitely realize how to
bring an issue to light and make it important. More and more people
ought to check this out and understand this side of
your story. It’s surprising you aren’t more popular given that you definitely have the gift.
Hi, Neat post. There’s a problem together with your site in internet explorer, might test this?
IE nonetheless is the market chief and a huge component to other
folks will omit your fantastic writing due to this problem.
Very nice post. I just stumbled upon your blog and wished to mention that I
have really loved browsing your weblog posts. In any case I will be subscribing for
your feed and I’m hoping you write again very soon!
We are a gaggle of volunteers and starting a new scheme
in our community. Your web site provided us with valuable info to work on. You
have done a formidable job and our whole group will probably be thankful to you.
Thanks in favor of sharing such a nice opinion, paragraph is fastidious, thats why i have read it
fully
Hello i am kavin, its my first occasion to commenting anyplace, when i
read this piece of writing i thought i could also make comment due to this good article.
Hello there! Do you use Twitter? I’d like to follow you if that would
be ok. I’m definitely enjoying your blog and look forward to new updates.
[url=https://vardenafil.cfd/]vardenafil 20mg generic[/url]
[url=https://clomid.digital/]buy cheap clomid[/url]
Наша команда опытных мастеров проштудирована предъявить вам перспективные методы, которые не только ассигнуруют надежную покров от прохлады, но и подарят вашему дому современный вид.
Мы занимаемся с последовательными компонентами, заверяя прочный срок службы эксплуатации и превосходные результирующие показатели. Изолирование внешней обшивки – это не только сокращение расходов на огреве, но и забота о экологии. Спасательные технологические решения, какие мы претворяем в жизнь, способствуют не только дому, но и сохранению природы.
Самое основополагающее: [url=https://ppu-prof.ru/]Утепление и штукатурка дома снаружи цена[/url] у нас стартует всего от 1250 рублей за м²! Это доступное решение, которое метаморфозирует ваш жилище в подлинный приятный местечко с минимальными затратами.
Наши труды – это не исключительно изоляция, это образование помещения, в где любой аспект символизирует ваш собственный манеру. Мы примем во внимание все твои запросы, чтобы осуществить ваш дом еще еще более удобным и привлекательным.
Подробнее на [url=https://ppu-prof.ru/]http://www.ppu-prof.ru/[/url]
Не откладывайте занятия о своем жилище на потом! Обращайтесь к спецам, и мы сделаем ваш жилище не только теплым, но и модернизированным. Заинтересовались? Подробнее о наших предложениях вы можете узнать на портале. Добро пожаловать в пространство благополучия и качества.
Мы служба SEO-специалистов, занимающихся увеличением посещаемости и рейтинга вашего сайта в поисковых системах.
Мы достигли значительных результатов и готовы поделиться с вами нашими знаниями и опытом.
Какие преимущества вы получите:
• [url=https://seo-prodvizhenie-ulyanovsk1.ru/]seo стоимость[/url]
• Комплексный анализ вашего сайта и разработка индивидуальной стратегии продвижения.
• Улучшение контента и технических параметров вашего сайта для максимального эффекта.
• Регулярное отслеживание и анализ результатов, с целью постоянного улучшения вашего онлайн-присутствия.
Подробнее [url=https://seo-prodvizhenie-ulyanovsk1.ru/]https://seo-prodvizhenie-ulyanovsk1.ru/[/url]
Клиенты, с которыми мы работаем, уже видят результаты: увеличение трафика, улучшение позиций в поисковых системах и, конечно же, рост прибыли. У нас есть возможность предоставить вам бесплатную консультацию, для того чтобы обсудить ваши требования и разработать стратегию продвижения, соответствующую вашим целям и финансовым возможностям.
Не упустите возможность улучшить свои позиции в интернете. Свяжитесь с нами прямо сейчас.
buying prescription drugs in mexico online: mexico pharmacy – mexican online pharmacies prescription drugs
indian pharmacies safe https://indiaph24.store/# reputable indian online pharmacy
top 10 pharmacies in india
http://indiaph24.store/# Online medicine home delivery
pharmacies in mexico that ship to usa: Mexican Pharmacy Online – buying from online mexican pharmacy
safe online pharmacies in canada [url=https://canadaph24.pro/#]canadian pharmacies[/url] canadian pharmacy scam
reputable indian pharmacies http://indiaph24.store/# reputable indian online pharmacy
top 10 pharmacies in india
http://indiaph24.store/# indian pharmacy online
http://mexicoph24.life/# mexican border pharmacies shipping to usa
tamoxifenworld: tamoxifen dosage – tamoxifen rash
https://nolvadex.life/# buy tamoxifen
buy generic ciprofloxacin [url=https://ciprofloxacin.tech/#]cipro[/url] cipro 500mg best prices
http://nolvadex.life/# tamoxifen bone pain
zestoretic 20 25 mg [url=https://lisinopril.network/#]lisinopril 60 mg tablet[/url] zestril 20 mg tab
40 mg lisinopril for sale: best generic lisinopril – lisinopril 15mg
https://nolvadex.life/# tamoxifen blood clots
https://lisinopril.network/# where to buy lisinopril without prescription
cost generic propecia without insurance [url=https://finasteride.store/#]buying cheap propecia prices[/url] cost of cheap propecia prices
cytotec buy online usa [url=http://cytotec.club/#]cytotec pills buy online[/url] cytotec online
nolvadex for sale amazon: where can i buy nolvadex – tamoxifen and osteoporosis
https://ciprofloxacin.tech/# purchase cipro
https://ciprofloxacin.tech/# buy cipro online canada
buying cheap propecia prices [url=http://finasteride.store/#]propecia online[/url] cost of generic propecia without prescription
https://lisinopril.network/# zestril online
buy cytotec over the counter [url=https://cytotec.club/#]buy cytotec over the counter[/url] cytotec abortion pill
buy nolvadex online: tamoxifen hormone therapy – liquid tamoxifen
https://cytotec.club/# Abortion pills online
buy propecia without prescription [url=https://finasteride.store/#]buy propecia[/url] cost of propecia without dr prescription
buy cipro online: ciprofloxacin over the counter – ciprofloxacin generic
http://nolvadex.life/# tamoxifen dose
https://nolvadex.life/# п»їdcis tamoxifen
buy cipro online canada [url=https://ciprofloxacin.tech/#]buy ciprofloxacin over the counter[/url] п»їcipro generic
order propecia [url=https://finasteride.store/#]cost generic propecia without insurance[/url] propecia without rx
https://cytotec.club/# Abortion pills online
https://finasteride.store/# cheap propecia without insurance
tamoxifen hair loss: tamoxifenworld – nolvadex for sale
Abortion pills online [url=https://cytotec.club/#]buy cytotec online fast delivery[/url] cytotec pills buy online
https://lisinopril.network/# 90 lisinopril
generic propecia pill: buying generic propecia pills – cheap propecia without prescription
lisinopril in mexico [url=https://lisinopril.network/#]lisinopril 80mg[/url] cheapest lisinopril 10 mg
https://nolvadex.life/# tamoxifen and antidepressants
buy generic ciprofloxacin [url=http://ciprofloxacin.tech/#]ciprofloxacin 500 mg tablet price[/url] antibiotics cipro
cipro online no prescription in the usa [url=http://ciprofloxacin.tech/#]cipro for sale[/url] buy cipro online without prescription
http://cytotec.club/# purchase cytotec
ciprofloxacin 500mg buy online: cipro for sale – buy ciprofloxacin
http://lisinopril.network/# cost of lisinopril in mexico
tamoxifen hip pain [url=http://nolvadex.life/#]common side effects of tamoxifen[/url] is nolvadex legal
https://finasteride.store/# order cheap propecia pill
nolvadex estrogen blocker: tamoxifen and ovarian cancer – tamoxifen citrate pct
cytotec abortion pill [url=http://cytotec.club/#]buy misoprostol over the counter[/url] buy cytotec
http://cytotec.club/# cytotec online
purchase cipro [url=http://ciprofloxacin.tech/#]buy cipro online[/url] ciprofloxacin mail online
http://finasteride.store/# buying propecia without prescription
cytotec pills online: Cytotec 200mcg price – buy cytotec pills
https://ciprofloxacin.tech/# purchase cipro
Misoprostol 200 mg buy online [url=https://cytotec.club/#]Misoprostol 200 mg buy online[/url] п»їcytotec pills online
https://cytotec.club/# Misoprostol 200 mg buy online
does tamoxifen cause weight loss: buy nolvadex online – does tamoxifen cause weight loss
tamoxifen buy [url=http://nolvadex.life/#]common side effects of tamoxifen[/url] alternative to tamoxifen
Kamagra 100mg price: buy kamagra online – Kamagra 100mg price
https://viagras.online/# Cheap Viagra 100mg
Cheap Levitra online [url=https://levitrav.store/#]levitrav.store[/url] п»їLevitra price
https://kamagra.win/# Kamagra Oral Jelly
Levitra 10 mg best price: Levitra 20mg price – Vardenafil online prescription
Cenforce 100mg tablets for sale: Cenforce 150 mg online – order cenforce
https://levitrav.store/# Generic Levitra 20mg
cheapest cialis [url=https://cialist.pro/#]Generic Cialis without a doctor prescription[/url] Generic Cialis without a doctor prescription
Purchase Cenforce Online: Cenforce 100mg tablets for sale – cenforce.pro
http://kamagra.win/# Kamagra 100mg price
http://viagras.online/# viagra canada
Cheap Cialis [url=https://cialist.pro/#]cialist.pro[/url] Cialis 20mg price in USA
Levitra online pharmacy [url=http://levitrav.store/#]Levitra 20mg price[/url] п»їLevitra price
Generic Cialis without a doctor prescription: buy cialis overseas – Generic Tadalafil 20mg price
https://viagras.online/# cheap viagra
http://kamagra.win/# Kamagra 100mg price
cheap kamagra: kamagra oral jelly – Kamagra 100mg
Cheap Sildenafil 100mg [url=http://viagras.online/#]Buy Viagra online[/url] viagra without prescription
Buy Cenforce 100mg Online: order cenforce – Purchase Cenforce Online
https://cenforce.pro/# cheapest cenforce
п»їkamagra [url=http://kamagra.win/#]kamagra.win[/url] sildenafil oral jelly 100mg kamagra
cenforce for sale: Cenforce 150 mg online – cenforce.pro
https://kamagra.win/# п»їkamagra
best online pharmacy india: indian pharmacy – india pharmacy mail order
mexico drug stores pharmacies: best online pharmacies in mexico – mexican drugstore online
http://pharmworld.store/# canadian pharmacy world coupon
https://pharmworld.store/# cheap pharmacy no prescription
mexican rx online [url=http://pharmmexico.online/#]mexican online pharmacies prescription drugs[/url] medicine in mexico pharmacies
canadian pharmacy mall: canadianpharmacy com – northern pharmacy canada
buying from online mexican pharmacy: buying prescription drugs in mexico – mexican rx online
https://pharmcanada.shop/# canada pharmacy world
pharmacy coupons [url=http://pharmworld.store/#]pharm world[/url] canadian online pharmacy no prescription