0
votes

I'm creating my own wordpress theme which is a bit different because it will not have single pages (or atleast, no single page will be reachable). The whole website contains just the homepage (with the loop) and previous posts pages.

I want to link to individual posts inside the loop like site.com#post-124 or site.com/paged=5#post-214.

I already created a function that does this:

function getPermalink($id,$postsPerPage) {
    $postNumber = Get_Post_Number($id); 
    //a function that get's the post number based on 
    //the chronical order of published posts.
    $page = floor(($postNumber - 1) / $postsPerPage);
    $url = get_option('home');

    if($page > 0) {
        $url .= '/?paged=' . ($page + (1 - floor($page / 5)));
    }

    $url .= '#post-' . $id;
    return $url;
}

You can see it live here: http://mijnrealiteit.nl (the previous posts pages are replaced by an infite scroll plugin).

This works, however it breaks when I start adding posts because all the posts before will get shifted back to pages further away (this makes the link invalid).

The way I see it there are two possible solutions:

  1. Change the permalinkstructure to display paging backwards (so x.com/paged=231 becomes the first 'previous' page. However this is not userfriendly.
  2. Make links with just the ID and let wordpress handle custom redirection to the page at that current point in time.

Are there better alternatives? I'm sure this is already solved somewhere, I just couldn't find it.

1

1 Answers

1
votes

I got pushed in the right direction by a friend, I build it quite easily using option 2:

The getPermalink function is now much simpler:

function getPermalink($id) {
    return get_option('home') . '/?f=' . $id;
}

I didn't make any custom redirection, I just checked at the homepage for a an 'f' being passed in the GET request:

$perma = $_GET['f'];
if(isset($perma) && !is_paged()) {
    $customposts = get_posts('p=' . $perma ); 
    foreach( $customposts as $post ) : 
        setup_postdata($post); ?>
            //load the post
    <?php endforeach;  
}?> 

If that is true the post will be fetched using the get_posts function by Wordpress. I also check the (normal) loop for the post that already has been served:

<?php while (have_posts()) : the_post(); 
    if(get_the_ID() != $perma) { ?>
        //load the post
<?php } endwhile; ?>