Preamble
In my functions.php
file I added a custom shortcode. This shortcode takes a query as a parameter and queries the wordpress database. From there it takes the posts content and returns it. This shortcode is then used on a non-custom page.
The issue
Using the shortcode on any page with a given and correct query, the shortcode will display the properly formatted content, but twice. This is although the query only returns one post.
So let's say I had [query_post query='post_type="post"']
on a page. The shortcode returns all posts of the type post
(which in my example is just one). The content is displayed fine, but at the end of the page the already displayed content repeats again. Why is this?
The code
In the functions.php
I appended this:
function query_post_shortcode_function( $atts ) {
// Argument parsing
$arguments = shortcode_atts( array(
'query' => "",
), $atts );
// Query
$posts = query_posts( $arguments['query'] );
// Getting the content for each queried post
unset($content);
foreach ($posts as $post) {
$content .= apply_filters( 'the_content', $post->post_content );
}
return wpautop($content);
}
add_shortcode( 'query_post', 'query_post_shortcode_function');
Which, as I've stated already, will query the wordpress database for a post and then return its content.
Steps taken already
- Instead of appending the content from all posts, I tried just assigning it. So
$content = apply_filters(...)
insted of.=
. This did not change the result - Echoing something inbetween will show in the first iteration of the returned content, but not in the second one
return wpautop($content);
toreturn "some string";
do you see "some string" twice or just once? If the shortcode is used just once and you only see one "some string" then the problem is with your post query.query_posts()
. codex.wordpress.org/Class_Reference/WP_Queryquery_posts
is bad. here's a stack overflow answer that's a bit simpler explaining the different ways you can query the database for posts. https://wordpress.stackexchange.com/questions/1753/when-should-you-use-wp-query-vs-query-posts-vs-get-posts