1

I came across this thread How to put custom post types on front page (thanks to @Andy Macaulay-Brook for the code)

and was able to use that code in my front-page.php to output portfolio items via twentysixteen child theme. It did work by putting <?php wpse_242473_recent_posts(); ?> into front-page.php however its not working when I am putting [recentposts] into the visual editor on 'work' page which is using front-page.php

I don't have much knowledge about PHP just some basics but out of curiousity I tried to google some parts of the function and what they mean and then modify the code slightly and remove parts related to shortcode (as shortcode was not working). Now I removed below parts and its working for me.

I have 3 questions:

  1. Do I need to use shordcode or this function can be used without shortcode portion?

  2. Did I use echo $out; correctly to output the result of the function to the browser?

  3. I already have my html markup for this page. Can I use this function to output my html into the browser or I should hardcode some html actually into my front-page.php?

Below are the changes I made to this function:

$atts = null, $content = null, $tag = null

(I removed those shortcode arguments)

I changed this part

if ( $tag ) {
   return $out;
    } else {
   echo $out;
 }

to this

    echo $out;

I also removed add_shortcode( 'recentposts', 'wpse_242473_recent_posts' );

So my current code looks like this

    function wpse_242473_recent_posts() {

      $out = '';

      $args = array( 
          'numberposts' => '6', 
          'post_status' => 'publish', 
          'post_type' => 'portfolio' ,
      );

      $recent = wp_get_recent_posts( $args );

      if ( $recent ) {

          $out .= '<section class="overview">';

          $out .= '<h1>Recent Projects</h1>';

          $out .= '<div class="overview">';

          foreach ( $recent as $item ) {

              $out .= '<a href="' . get_permalink( $item['ID'] ) . '">';
              $out .= get_the_post_thumbnail( $item['ID'] ); 
              $out .= '</a>';
          }

          $out .= '</div></section>';
      }


        echo $out;


    }

added Custom Post Type code for review (portfolio-type.php)

<?php

/*
* Sets 'Portfolio' CPT (Custom Post Type) in admin screen and .
* This template is loaded to functons.php in child theme via 'require_once' function        
*/



//set thumbnail size and image size

function portfolio_thumb_and_image_size () {

  set_post_thumbnail_size( 280, 210, true); //thumb
  add_image_size ('screenshot', 720, 540); //image

}

add_action('after_setup_theme', 'portfolio_thumb_and_image_size', 17);

//add custom post type


function portfolio_register() {

  $args = array(

        'label' => __('Portfolio'),
        'singular_label' => __('Project'),
        'public' => true,
        'show_ui'=> true,
        'capability_type' => 'post',
        'hierarchical' => false,
        'rewrite' => true,
        'supports' => array('title', 'editor', 'thumbnail') 
      );

      register_post_type('portfolio', $args);

}

add_action ('init', 'portfolio_register');


//add custom taxonomy

register_taxonomy ('project-type', array ('portfolio'), array('hierarchical' => true, 'label' => 'Project Types', 'singular_label' => 'Project Type', 'rewrite' => true));

//add custom fields


function portfolio_meta_box() {

add_meta_box ('project-meta', 'Project Options', 'portfolio_meta_options',  'portfolio', 'side', 'low');

}

add_action("admin_init", "portfolio_meta_box");

function portfolio_meta_options(){

      global $post;

      if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return $post_id;
      $custom = get_post_custom($post->ID);
      $link = $custom ['project-link'][0];
?>

<label>Link:</label><input name="project-link" value="<?php echo $link; ?>" />
<?php
 }

//save custom meta boxes when the post is saved


function save_project_link (){

      global $post;

      if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )  {
         return $post_id;
      }

      else  {

        update_post_meta ($post->ID, 'project-link', $_POST['project-link']);
      }
}

add_action ('save_post', 'save_project_link');

//customize admin columns

//add custom columns via filter hook (make columns available on the edit posts page)
function project_register_columns($columns) {
  $columns = array(
      'cb' => '<input type=\'checkbox\' />',
      'title' => 'Project',
      'description' => 'Description',
      'link' => 'Link',
      'type' => 'Type of Project',

  );
  return $columns;

}

add_filter('manage_edit-portfolio_columns', 'project_register_columns');

//add content to custom columns: 'description' 'link' 'type'
function add_columns_content ($columns) {
    global $post;
    switch ($columns)
    {

        case 'description':
            the_excerpt();
            break;

        case 'link':
            $custom = get_post_custom();
            echo $custom['project-link'][0];
            break;

        case  'type':
            echo get_the_term_list($post->ID, 'project-type', '', ', ','');
        break;

    }

}

add_action('manage_posts_custom_column', 'add_columns_content');



function wpse_242473_recent_posts() {
  $frontpage_args = array( 
      'numberposts'   => '6', 
      'post_status'   => 'publish', 
      'post_type'     => 'portfolio' ,
  );
  $recent = wp_get_recent_posts( $frontpage_args ); ?>
  <section class="overview">
      <h1>Recent Projects</h1>
      <div class="overview">
      <?php if( $recent ) :
          foreach ( $recent as $item ) : ?>
              <a href="<?php echo get_permalink( $item->ID ); ?>">
                  <?php echo get_the_post_thumbnail( $item->ID ); ?> 
              </a>
          <?php endforeach;
      endif; ?>
      </div>
  </section>
}

content of front-page.php

<?php 

get_header();

?>


<main class="home">

    <h1>this is front-page.php</h1>

    <?php wpse_242473_recent_posts(); ?>

    <!-- porfolio items go here ––>


</main>

<?php get_footer(); ?>
</div>
3
  • 1
    I recommend avoiding helper functions such as wp_get_recent_posts, they're their for historical reasons and tend to cause more problems than they're worth due to the little changes they make trying to be helpful. In this case, a standard WP_Query loop would cut out the middle man and be more in line with what most developers do, as well as what tutorials and WP code uses
    – Tom J Nowell
    Commented Apr 12, 2020 at 21:31
  • Thanks for the feedback Tom J Nowell. If you can give me a link or two to those tutorials that would help. I am new to WordPress and PHP and its very easy to find wrong info on the web with bad practices hence I am asking if you can refer me to some reliable tutorials
    – 810311
    Commented Apr 14, 2020 at 2:57
  • Aside from checking how recent a tutorial is, if you need to fetch/display posts, use WP_Query. If you want to change what WP shows in the main loop, use the pre_get_posts filter. For how to use a WP function, always check the official dev docs at developer.wordpress.org, and the comments on their pages
    – Tom J Nowell
    Commented Apr 14, 2020 at 9:16

1 Answer 1

0

Ok, completely re-written answer based on previous attempts and some suggestions from the comments (which I agree with as I've never used wp_get_recent_posts() myself...

Assuming that everything for your custom post type is working correctly (I didn't test it though) then just use the following for your front-page.php.

<?php get_header(); ?>
<main class="home">
    <h1>This is front-page.php</h1>
    <?php
    $fp_portfolio_args  = array(
        'post_type'         => 'portfolio',
        'post_status'       => 'publish',
        'posts_per_page'    => 6
    );
    $fp_portfolio_query = new WP_Query( $fp_portfolio_args );
    if( $fp_portfolio_query->have_posts() ) : ?>
    <section class="overview">
        <h2>Recent Projects</h2>
        <div class="overview">
        <?php while ( $fp_portfolio_query->have_posts() ) : $fp_portfolio_query->the_post(); ?>
            <a href="<?php echo get_permalink( $post->ID ); ?>">
                <?php echo get_the_post_thumbnail( $post->ID ); ?> 
            </a>
            <?php $link = get_post_meta( $post->ID, 'project-link', true ); ?>
            <a href="<?php echo $link; ?>">View Project</a>
        <?php endwhile; ?>
        </div>
    </section>
    <?php endif;
    wp_reset_query(); ?>
</main>
<?php get_footer(); ?>
</div>
11
  • thanks for the feedback Tony Djukic. I am not sure I fully understand few lines from this function. Say is it a standard practice just to put html tags inside the function? like I am seeing here h1, section, divs, etc...
    – 810311
    Commented Apr 14, 2020 at 4:09
  • Also why do we need to wrap 'foreach' statement inside 'if'? Also what is $item->ID ? My understanding anything with $ sign is a variable which kind of serves as a container for other things, however, I don't understand what is the purpose of -> after variable name..
    – 810311
    Commented Apr 14, 2020 at 4:19
  • I added to my answer to address your follow-up questions. Did you try the code? Full disclosure, I've never used wp_get_recent_posts() but when I checked online it's basically just a prepared wp_query(). developer.wordpress.org/reference/functions/wp_get_recent_posts/… You can see in that example that the HTML is just placed into the function. Commented Apr 14, 2020 at 5:03
  • Hi Tony, thanks for the detailed explanations. I just tried your code and it didn't work.
    – 810311
    Commented Apr 15, 2020 at 1:38
  • Sure. The error I am getting is 'Parse error: syntax error, unexpected end of file'
    – 810311
    Commented Apr 15, 2020 at 1:41

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.