elementor / elementor/elementor
Post Single Template fail to open with my Shortcode Plugin (get_posts())
- Dominant language
- PHP
- Stars
- 7.1k
- Forks
- 1.6k
- Avg merge
- 1d 5h
- Merged PRs (30d)
- 193
Description
I created this shortcode plugin to loop and display the posts. It has `get_posts()` function in it. When added the shortcode to a Single Post Template in Elementor the editor fails to open. It says "`You must call the_content function in the current template`"
I first thought of reseting the loop data with `wp_reset_query()` or `wp_reset_postdata()`. But that didn't solve.
Any insights on what is causing this?
Here is my code:
```
if (!function_exists('post_loop_shortcode')) {
function post_loop_shortcode($atts)
{
$a = shortcode_atts(array(
'pagination'=> '',
'number' => 6,
'offset' => 0,
'category' => '',
), $atts);
// Get the Total Number of Posts
$totalPosts = wp_count_posts()->publish;
// Args array to pass on to get_posts()function, data comes from shortcode atts
$args = array(
'numberposts' => $a['number'],
'offset' => $a['offset'],
'category' => $a['category'],
);
// Loops through all posts returned from get_posts() and build the card HTML
$cardsHTML = '';
$posts = get_posts($args);
wp_reset_postdata();
foreach ( $posts as $post) {
// Get variables that will be used in HTML
$postImage = get_the_post_thumbnail($post->ID, 'large');
$postTitle = $post->post_title;
$postLink = get_permalink($post->ID);
$postDate = date('F d, Y', strtotime($post->post_date));
$categoryTitle = get_the_category($post->ID)[0]->name;
$categoryLink = get_category_link(get_the_category($post->ID)[0]->term_id);
// Build the card HTML
$cardHTML = '
// HTML code goes here
';
// Append all cards to $cardsHTML
$cardsHTML = $cardsHTML . $cardHTML;
}
// Build the whole HTML
$postLoopHTML = '
' . $cardsHTML . '
' . $isPagination . '
';
if (!wp_style_is('post-loop-css', 'enqueued')) {
wp_enqueue_style('post-loop-css');
}
if (!wp_script_is('post-loop-js', 'enqueued')) {
// Only enque JS if pagination is set to true
if ($isPagination) {
wp_enqueue_script('post-loop-js');
}
}
// Return the shortcode HTML
return $postLoopHTML;
}
}
add_shortcode('post_loop', 'post_loop_shortcode');
```
Contributor guide
Research direction
Start by reproducing the failure in an Elementor Single Post Template with the provided post_loop shortcode, then inspect the shortcode function and its get_posts() loop. Compare behavior with and without the shortcode and determine why the editor reports that the current template must call the_content function. Done means the template editor opens while the shortcode still renders its post cards.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- php
- Domain
- frontend, web-dev
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100