- This topic has 3 replies, 3 voices, and was last updated 3 years, 1 month ago by David.
-
AuthorPosts
-
February 23, 2021 at 1:55 pm #1669771Dan
Hi
I’m adding a php loop to an element hook, with a function which resides in the functions.php file.
when doing so, I get a fatal error regarding GPP hook file.
If I move over the complete code, including the function into the element, it works ok.
Is there a specific condition that I should apply when splitting between elements and the functions.php?The complete code is here:
<?php global $post; $current_category = get_the_category(); $same_category = new WP_Query(array( 'cat' => $current_category[0]->cat_ID, 'post__not_in' => array($post->ID), 'orderby' => 'rand', 'posts_per_page' => 15 )); ?> <div class="other-series"> <h4>Other Series:</h4> <ul> <?php while ( $same_category->have_posts() ) : $same_category->the_post(); ?> <li> <div class="item"> <?php if ( has_post_thumbnail()) : ?> <a href="<?php the_permalink(); ?>" alt="<?php the_title_attribute(); ?>"> <?php the_post_thumbnail('thumbnail'); ?> </a> <?php endif; ?> <a href="<?php the_permalink(); ?>"> <h2><?php the_title(); ?></h2> </a> </div> </li> <?php endwhile; ?> </ul> </div>
Originally, the php code up to the
<div class="other-series">
was in the functions.php file.Thanks,
DanFebruary 23, 2021 at 4:38 pm #1669947ElvinStaffCustomer SupportHi there,
If I may suggest a way to do this:
Try adding this snippet to your
functions.php
.add_shortcode('post_loop',function(){ ob_start(); shortcode_loop(); return ob_get_clean(); }); function shortcode_loop(){ global $post; $current_category = get_the_category(); $same_category = new WP_Query(array( 'cat' => $current_category[0]->cat_ID, 'post__not_in' => array($post->ID), 'orderby' => 'rand', 'posts_per_page' => 15 )); ?> <div class="other-series"> <h4>Other Series:</h4> <ul> <?php while ( $same_category->have_posts() ) : $same_category->the_post(); ?> <li> <div class="item"> <?php if ( has_post_thumbnail()) : ?> <a href="<?php the_permalink(); ?>" alt="<?php the_title_attribute(); ?>"> <?php the_post_thumbnail('thumbnail'); ?> </a> <?php endif; ?> <a href="<?php the_permalink(); ?>"> <h2><?php the_title(); ?></h2> </a> </div> </li> <?php endwhile; ?> </ul> </div> <?php }
You then call this snippet with the
[post_loop]
shortcode on your Hook Element. Just make sure to haveExecute Shortcode
enabled.February 24, 2021 at 7:12 am #1670765DanThanks Elvin,
As creating a shortcode is a legit solution, I was wondering if there is a way to keep the function in functions.php and the html in the element, seperated. Wondering if this is a priority issue or something else and what would be the best practice going forward.Thanks!
DanFebruary 24, 2021 at 7:42 am #1670809DavidStaffCustomer SupportHi there,
the query would need to be wrapped in its own function – heres a similar example:
-
AuthorPosts
- You must be logged in to reply to this topic.