• Scenario: I have a CPT called “Market Reports.”

    I want the most recently published Market Report to use is_user_logged_in to only show to logged in users. Non-logged-in uses are displayed a login form. Logged-in users are shown the post content.

    I know I can do this manually by simply creating two different single.php templates and changing them when I create a new post.

    However, is there any way to use some code in the template to check if there is a more recent market report post and do this dynamically?

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz

    (@bcworkz)

    It doesn’t make sense to always display the latest report on single.php, which could be used for any archived report as well. What I would do is create a “latest” page which always queries for the latest report. This can be done by creating a custom template just for this specific page. If you name the template like this: "page-{$slug}.php", it’ll only be used for the page named $slug. You can still do a login check and redirect to the login page or display a local login form with template code.

    Thread Starter oguruma

    (@oguruma)

    @bcworkz I’m not sure I’m following what you’re saying.

    I was planning on creating a single-reports.php for the Market Reports CPT.

    I know how to use the is_user_logged_in function, but what I don’t know how to do is programmatically check if there is a newer Market Report….

    Moderator bcworkz

    (@bcworkz)

    single-reports.php is fine for single reports whose permalink always leads to the same content. A “latest” report page which has ever changing content should be handled differently. I’m suggesting a separate page-recent.php template (assuming the added page’s slug is “recent”) On this template you can call get_posts() to get the most recent report. Include args for the post type, and set the posts_per_page arg to 1. As the default ordering is descending date, you’ll always get the most recent report. It wouldn’t be a bad thing to explicitly specify ordering by descending date all the same just so your code is more clear about its intent.

    The most recent post object will be returned as the first and only element in an array. You can output post object properties as you normally would. We normally still run a foreach loop even if there’s only one post returned, but it’s not really necessary. You could even do something like echo get_posts( $args )[0]->post_content;, but you’d likely want to assign the return to a variable. Normally we’d do a loop similar to the first to examples on the WP_Query docs page. get_posts() is essentially a wrapper function for a new WP_Query instance.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Different template for most recent post?’ is closed to new replies.