How To Implement A News Page In WordPress From Scratch – Part 1
In this Tutorial I will show you how to add a new wordpress page to your website.
You will see, we will implement this page with few lines of code and everything will work as expected.
The HTML and PHP code are here:
<?php
/*
* Template Name: News
*/
?>
<?php get_header();?>
<section id="breaking_news" class="breaking_news">
<div clas="main_slider_news">
<div class="item">
<div class="container">
<div class="category_name">
<h2></h2>
</div>
<div class="post_title">
<a href=""></a>
</div>
<div class="read_more_btn">
<a href="">Citeste mai mult</a>
</div>
</div>
</div>
</div>
</section>
<?php
$news_posts_args = array(
'post_type' => 'post',
'posts_per_page' => -1
);
$news_posts = get_posts($news_posts_args);
?>
<?php if($news_posts):?>
<section id="main_news_section" class="main_news_section">
<div class="container">
<div class="section_name">
<h2>Stiri</h2>
</div>
<div class="news_container">
<?php foreach($news_posts as $k => $v):?>
<?php
$news_image = wp_get_attachment_image_src( get_post_thumbnail_id( $v->ID ), 'big_square');
?>
<div class="post_item">
<div class="table_row">
<div class="left">
<div class="background" style="background-image:url(<?=$news_image[0];?>)"></div>
</div>
<div class="right">
<div class="title">
<a href="<?=get_permalink($v->ID);?>"><?=$v->post_title;?></a>
</div>
<div class="description">
<?=strip_tags(substr($v->post_content, 0, 200));?> [...]
</div>
</div>
</div>
</div>
<?php endforeach;?>
</div>
</div>
</section>
<?php endif;?>
<?php get_footer();?>
get_header(); - is a wordpress function which return the header. In wordpress case it will return the 'header.php' file
get_footer(); - the same as get_header(); get_footer(); will return the 'footer.php' file.
We have there $news_posts_args var
in this variable we save the post_type which want to be retrieved from Wordpress, and posts_per_page refer to how many posts should appear on the page. -1 stand for unlimited.
With get_posts() function we get all posts from wordpress db, then in the foreach loop we access every post and create the html for it.
The full video for Part 1 of this tutorial is below:
Let me know if you have any questions.