php – Create a custom plugin with dynamic child pages listing database records

Question

I am developing a simple lean and mean custom plugin which has the purpose to list records from some database tables. Goal is to list data via url /teams/{category}/{id}.

I’ve created a basic plugin and a “teams” page and added a short code to fetch a list of teams:

// upcoming events shortcode
function test_teams_overview() {
    $output="";
    global $wpdb;
    $teams = $wpdb->get_results('SELECT * FROM Teams');
    if(count($teams)){
        $output .= '<ul>';
        foreach($teams as $team){
            $output .= '<li><a href="/' . $team->url . '">' . $team->team . '</a></li>';
        }
        $output .= '</ul>';
    }
    else{
        $output .= '<p>No teams :( </p>';
    }
    return $output;
}
add_shortcode('teams', 'test_teams_overview');

This works, but I am stuck on the next part, which action/hook to use to list dynamic subpages. Clicking in the above example leads to an URL like /teams/alpha. By adding an custom hook I can get control over the URI requested, however I can’t get the output “injected” in the template/page (gives a 404), this is what I have:

add_action( 'init', 'teams_custom_router' );
function teams_custom_router( $query ) {
    global $wp_query;
    exit(print_r($wp_query,1)); 
}

The teams_custom_router() can’t help me any further as $wp_query remains empty. I can’t get it to work to inject a custom/view template listing database records based upon the URI.
I’ve also worked with taxonomy and custom rewrite rules, but no working proof of concept so far.

Question

  • How can I create a setup whereas I can call my plugin via a shortcode (e.g. [teams]) which subsequently lists records from separate db tables via a dynamic URL (/teams/{category}/{id}/{more params}

Unfortunately I can’t find any snippet or good reference (plugin example) for this use case. Anyone some clever ideas?

Thanks!

0
Flapoor 4 days 2023-03-18T11:31:21-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse