New to php, but I’ve learned how it works (I mean, I can write php and do the things in the YouTube tutorials). I’m having difficulty applying it to actual use though:
I want to shorten the amount of php I need to put on frontpage.php (WordPress, but I hear this question is not a WordPress question; just a php one).
I’m going to call the same php many times to display 1 post each time, just changing the category to display in the php – so, now I have:
lots of php cat=33 lots of php
I want to make a function so that on my frontpage.php, I just need to write:
whatever cat=33 whatever
or just
whatever 33
If it helps to have my code, it is (this has tag, but I use both tag and cat here and there):
<?php
$args=array(
'tag' => 'feature-left',
'showposts'=>1,
'caller_get_posts'=>1
);
$my_query = new WP_Query($args);
$offset = 3;
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>" itemscope="itemscope" itemtype="http://schema.org/BlogPosting" itemprop="blogPost">
<h4><?php the_excerpt(); ?> </h4>
</a>
<a href="<?php the_permalink() ?>" >
<div class="front-first-article-title" itemprop="headline"><h2 style="color:#00589C; margin-bottom:5px;"><b><?php the_title(); ?></b></h2>
</div>
<?php
endwhile;
} //if ($my_query)
wp_reset_query(); // Restore global post data stomped by the_post().
?>
In your theme folder, find your functions.php file.
In that file, place this code (from your question) into a function, like so:
Now, in your home page file, you can drop in
my_custom_loop(33)
to have it output your custom post loop.NOTE
There’s a few issues with your HTML inside your loop. You shouldn’t put
<div>
or<h2>
or<h4>
elements inside of an<a>
tag. Also, your<a>
tag is not getting closed properly. Lastly, I’d suggest using classes / CSS rather than inline styles on your<h2>
, as it’s going to be output to the screen many times, and it’s sorta silly to output the exact same inline CSS a bunch of times.EDIT
Per your recent comments, yes, you could make the function also handle tags, and have the “number” be dynamic. Note that there are a variety of approaches to this sort of issue, but the most direct (given your existing function) would be something like so:
if you dont want your functions to be crowded you can create folder lets call it
templates/parts/
for each part you want to reuse put inside one
.PHP
file .then any where you need this block you call it
this is better from design prospective . for example the main page for one website I am building looks like this
and I have all the files for each parts in one folder I can move them to other project or when there is problem it easer to go to file other than go to function in 1 big function.php