Custom PHP Link Tree with Dynamic Latest Post URL
As a web developer nerd, it was unthinkable to use a WordPress plugin to create a “link tree” for my socials. It was a fun project one night to write up an HTML page with custom CSS and drop it into the webserver. However, I quickly realized that I wanted a dynamic link to the latest post rather than updating it manually each time I published. I scoured the web for a quick solution and while I found many people who were also searching for the same thing, nothing was quite working for my use case. In this post, we will create a custom link tree in PHP at the root of the word press server which has a link to the latest post.
The PHP Code 🤖
It is important to make this file at the root. I tried putting it in a folder but the includes are finicky and it seems to work best operating at the root level.
<!--links.php-->
<?php
require('./wp-load.php');
$args = array(
'post_type' => 'post',
'post_status' => 'publish'
);
$all_posts = get_posts($args);
$title = $all_posts[0]->post_title;
$link = $all_posts[0]->guid;
?>
<div>
<a class= "myButton" href="<?=$link ?>" target="_blank">
Latest Post: <?= $title?>
</a>
</div>
The require statement1 How to use WP Functions “outside of” WP: https://wordpress.stackexchange.com/questions/47049/what-is-the-correct-way-to-use-wordpress-functions-outside-wordpress-files lets us use WordPress functions. The get_posts
2 Docks for get_post
: https://developer.wordpress.org/reference/functions/get_posts/ function is fetching the latest posts (I think by default, the first published 4) as an array of WP_Post
objects. You can grab the post_title
and the guid
to use in an HTML link or however you please in the rest of the PHP file!
The Fun Part, CSS + HTML
Creating a link tree is a great beginner project and if you inspect mine using dev tools you can see my custom CSS and the simple styling that makes this page mobile-friendly. My main goal in this was to get rid of the extra WordPress themes and menus when I’m simply trying to direct people to a few interesting links or other socials.
The WordPress solution to getting the latest post is to use a plugin short-code or their built-in “latest posts” block. I thought the block looked ugly and the plugin is for use inside of your WordPress posts or pages. I also wanted complete control over the styling and social media icons etc. This project is probably the first in a slow process of building my own website from scratch.
Good luck to the other beginner PHP/WordPress developers that might find a use for this very specific code snippet!