Site logo

Archived topic

using elements with function.php

3 replies · Started by Dan on February 23, 2021

Viewing posts 1–4 of 4

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,
Dan

Hi 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 have Execute Shortcode enabled.

Thanks 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!
Dan

This archived topic is closed to new replies.