• For a client one-page website I am making I want to run a loop to get the latest three blog/news items to show on a page that uses child-pages as ‘sections’ of the page. I found a way to add a shortcode to output the loop on a sub-page, but it only returns the title of the parent page.

    The structure of my one-page website:

    – One Page (Parent)
    — About us
    — Menu
    — News (this is where I would like the loop)
    — Contact

    I use the Rosa theme.

    And here is the code I use in my functions.php:

    function custom_query_shortcode($atts) {
    
       // EXAMPLE USAGE:
       // [loop the_query="showposts=100&post_type=page&post_parent=453"]
    
       // Defaults
       extract(shortcode_atts(array(
          "the_query" => ''
       ), $atts));
    
       // de-funkify query
       $the_query = preg_replace('~&#x0*([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $the_query);
       $the_query = preg_replace('~&#0*([0-9]+);~e', 'chr(\\1)', $the_query);
    
       // query is made
       query_posts($the_query);
    
       // Reset and setup variables
       $output = '';
       $temp_title = '';
       $temp_link = '';
    
       // the loop
       if (have_posts()) : while (have_posts()) : the_post();
    
          $temp_title = get_the_title($post->ID);
          $temp_link = get_permalink($post->ID);
    
          // output all findings - CUSTOMIZE TO YOUR LIKING
          $output .= "<li><a href='$temp_link'>$temp_title</a></li>";
    
       endwhile; else:
    
          $output .= "nothing found.";
    
       endif;
    
       wp_reset_query();
       return $output;
    
    }
    add_shortcode("loop", "custom_query_shortcode");

    And I output it with: [loop query="posts_per_page=3"] in the page editor.

  • The topic ‘Loop returns parent-page’ is closed to new replies.