[PHP] How to Call a Piece of Code?

Skint

New member
Aug 16, 2010
163
0
0
Hi,

I know nothing about programming really in general, I can only guess when it comes to HTML, so bear with me!

Basically I have this same piece of code that I want to display on various parts of my site and I currently do and it works.

However, I want to try and clean the code up, so instead of having a huge code pasted on each page's source code, I want to have a simple php call function (I think it's that?) so that I just type a little code and it will call the bigger code from elsewhere.

Understand? Sorry if not... let me know if you don't please!

I'm using Wordpress by the way!

Thanks.
 


Well with php you can allways use the include function that would pretty much allow you to remove tons of repetitive code from a site. That's what wordpress does when it "includes" the header and footer among other things.

Since you are using wordpress, just include the repetitive code doing this: create a function and add it to your theme's functions page (every theme has it). Then, just call that function from every page were you want the code to be displayed. Simple.

Here's an example:

Create this function and post it on the functions.php file
Code:
function dickroll ()
{
     echo ("The end of the world is coming. Repent you fucking idiots. <br>Repent. Start that by giving me all your monies, I'll get you rid of that sinful crap!");
}

Then, let's suppose you wanted that code to be on each page of your site near the footer. The only thing you would have to do is paste the following code on the footer.php page and that's it.
Code:
<?php
dickroll ();
?>
 
Perfect answer! Nice little tutorial you just gave me, with very inventive examples!

Ha, thanks man.
 
I just tried it and it didn't work in my case... this was what my code looked like somewhat:


function button ()
{
echo ("<a id="page" href="http://mysite.com/page/"><span>Page</span></a>");
}

But it returned a PHP error; white background and black text. I was like fuark and quickly changed it back so I don't know what it said, but what I did must have been wrong in some way?

Thanks.
 
You mixed double quotes. Change the inner quotes to single quotes, or escape them with a backslash. Or read the PHP error ;)
 
Skint the problem is with the double quotes like Rish said, do it like this:

Code:
function button ()
{
echo ('<a id="page" href="http://mysite.com/page/"><span>Page</span></a>');
}
 
Another approach is to use file include
<?php include("filewithcode.php"); ?>

This will work for WP as well as in any PHP site. Put whatever you like in the filewithcode.php, then just include the code above wherever you want to call it.
 
Perfect answer!Thanks!
g.gif