-1

I ask this question as a follow-up to this one.

I have this query-function in functions.php but AAMOF I don't want to change functions.php at all (besides for CPTs).

I'd like to print the same data directly from WP GUI via shortcode.

How should a functions.php query-function be translated into a query-shortcode?

$posts = get_posts(array(
    "post_type"=>"book_pages",
    "post_status"=>"publish",
    "posts_per_page"=>-1 
));

if ($posts && count($posts)>0) 
{
    global $post;
    foreach ($posts as $post)
    {
        setup_postdata($post);
        the_title(); //prints out the title of this post
    }
    wp_reset_postdata(); 
}
1
  • There isn't a shortcode that does this. You would need to make it, but that would involve changing functions.php. Commented Aug 30, 2018 at 10:42

1 Answer 1

0

A shortcode is essentially a trigger that leads to execution of a piece of code in you functions.php file. The only real difference with the code you already have is you don't print the result immediately, but return it from the function. Also, get_posts is not the preferred way to do multiple loops, as you can see in the first paragraph in the codex. Better use wp_query directly. Like this:

add_shortcode ('wpse312883', 'wpse312883_query_shorcode' );

function wpse312883_query_shorcode () {
  $all_post_titles = "";
  $args = (array(
    "post_type"=>"book_pages",
    "post_status"=>"publish",
    "posts_per_page"=>-1 
    ));
  $the_query = new WP_Query( $args );
  if ( $the_query->have_posts() ) {
    while ( $the_query->have_posts() ) {
      $the_query->the_post();
      $all_post_titles .= get_the_title();
      }
    }
  wp_reset_postdata();
  return $all_post_titles;
  }

No, if you include [wpse312883] in your post content in the GUI you will get a list of post titles. You may want to add some html to $all_post_titles depending on how you want to format the result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.