I added a bit of custom HTML code to a website. Everything works just great. I am trying to display this HTML code based on the page name. I looked at some resources online and wrote out the code but it does not work. I have also checked online and I am only seeing ways to conditionally add CSS and JS. Is this something that is possible to do and how do I go about doing this?
My code
<?php
global $wpdb;
$query = new WP_Query(array(
'posts_per_page' => 12,
'category_name' => 'featured-posts',
));
$posts = $query -> posts;
if ( is_page('Featured Posts') ){
foreach ($posts as $post) {
echo '
<div class="slider-container">
<h4 class="slider-header">
<span class="slider-header_text">Trending</span>
</h4>
<div class="slider">
<div class="carousel-container">
<div class="carousel-inner">
<div class="track">
<div class="card-container">
<a href="'.$post->guid.'" class="card">
<div class="img">
<img src="'.get_the_post_thumbnail_url( $post -> ID, 'thumbnail' ).'" alt="">
</div>
<div class="info">
<h5>'.$post->post_title.'</h5>
</div>
</a>
</div>
</div>
</div>
<div class="nav">
<button class="prev">
<i class="fas fa-angle-left"></i>
</button>
<button class="next">
<i class="fas fa-angle-right"></i>
</button>
</div>
</div>
</div>
</div>';
}
}
?>
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
instead of echoing a whole bunch of html you can close your php tags and just write html as normal.
for example:
<?php
...
...
...
foreach ($posts as $post) {
?>
<!-- here goes the html -->
<?php
}
?>
On the otherhand you mention in your question that you are trying to display html based on a page name.
You can do this by making a page template
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0