• Resolved RoboPope

    (@robopope)


    Hi
    I have spent a few days googling and trying to covert the following working php code to a shortcode so it doesn’t get lost when the other two users update a page with the visual editor.

    <?php
      $page_links = get_posts(array(
        'category' => '25',
        'post_type' => 'page',
        'posts_per_page'=>-1,
        'post_status' => 'publish',
        'orderby' => 'title',
        'order' => 'ASC'
      ));
    
      foreach($page_links as $link){
        echo '
    <li><a>ID).'">'.$link->post_title.'</a></li>
    ';
      }
    ?>

    I don’t think the issue is with the array but the output but as a cut and paste coder as its not my primary role its somewhat beyond me. If someone could point out what I am not getting that would be great

    Thanks

    Paul

Viewing 5 replies - 1 through 5 (of 5 total)
  • Moderator Steven Stern (sterndata)

    (@sterndata)

    Volunteer Forum Moderator

    You can’t use echo in a shortcode. Either stuff all of the output into a string that the function returns or use ob_start() and return ob_end_flush()

    You can look up those two functions in the PHP manuals. String stuffing:

    function my_shortcode($atts, $content) {
       $page_links = get_posts(array(
        'category' => '25',
        'post_type' => 'page',
        'posts_per_page'=>-1,
        'post_status' => 'publish',
        'orderby' => 'title',
        'order' => 'ASC'
      ));
      $ret = "<ul>";
      foreach($page_links as $link){
        $ret .= '<li><a>ID).'">'.$link->post_title.'</a></li>';
        }
       $ret .= "</ul>";
       return $ret;
    Thread Starter RoboPope

    (@robopope)

    Thanks for the reply. I have tried to test this code in php rather than a short code declaration and I get.

    Parse error: syntax error, unexpected ‘”’ in /homepages/blah/blah/blah/blah/runtime.php(42) : eval()’d code on line 16 it seems to be unhappy with the single ” in the ‘”>’ part of the statement
    `
    foreach($page_links as $link){
    $ret .= ‘<li><a>ID).'”>’.$link->post_title.'</a></li>’;

    `

    Moderator Steven Stern (sterndata)

    (@sterndata)

    Volunteer Forum Moderator

    I don’t guarantee that I riff out error free code. 🙂

    There’s probably an extra quote or prime (or a missing one). The key thing is in how to do it, not the exact code.

    Thread Starter RoboPope

    (@robopope)

    lol point taken. Hopefully it has pointed me in the right direction

    Thank you 🙂

    Thread Starter RoboPope

    (@robopope)

    Resolved. I ended up using ob_start(); and return ob_get_clean(); around an ammended verison of my code

Viewing 5 replies - 1 through 5 (of 5 total)

The topic ‘Converting PHP code to shortcode help’ is closed to new replies.