How to make post-to-post link in WordPress?

The “post-to-post” relationship in WordPress can be implemented in several ways depending on your needs and technical expertise. Here are the main approaches:


1. Using Plugins

If you want to implement post-to-post relationships without coding, you can use ready-made plugins:

  • Advanced Custom Fields (ACF)
    ACF allows you to create a custom field (a “Post Object” field) to link posts. Here’s how to do it:
    1. Install and activate the ACF plugin.
    2. Create a field group with the “Post Object” or “Relationship” field type.
    3. Attach the field group to the necessary post types.
    4. Display the relationships in your templates using the get_field() function.
  • Pods Framework
    This plugin allows you to easily create relationships between posts, taxonomies, and even custom tables. It is highly flexible.
  • Toolset Types
    Another powerful plugin for working with custom post types and relationships.

2. Creating Custom Meta Fields

You can use meta fields to store the IDs of related posts.

Steps:

  • Add a custom field in a meta box for the post where you can choose another post:
function add_custom_metabox() {
    add_meta_box(
        'post_relationship_metabox',
        'Related Post',
        'render_post_relationship_metabox',
        'post',
        'side',
        'default'
    );
}
add_action('add_meta_boxes', 'add_custom_metabox');

function render_post_relationship_metabox($post) {
    $connected_post_id = get_post_meta($post->ID, '_connected_post', true);
    ?>
    <label for="connected_post">Select a related post:</label>
    <select name="connected_post" id="connected_post">
        <option value="">None</option>
        <?php
        $posts = get_posts(['post_type' => 'post', 'posts_per_page' => -1]);
        foreach ($posts as $p) {
            $selected = ($p->ID == $connected_post_id) ? 'selected' : '';
            echo "<option value='{$p->ID}' $selected>{$p->post_title}</option>";
        }
        ?>
    </select>
    <?php
}

function save_post_relationship_metabox($post_id) {
    if (isset($_POST['connected_post'])) {
        update_post_meta($post_id, '_connected_post', sanitize_text_field($_POST['connected_post']));
    }
}
add_action('save_post', 'save_post_relationship_metabox');
  • Retrieve the related post using meta data:
$connected_post_id = get_post_meta($post->ID, '_connected_post', true);
if ($connected_post_id) {
    $connected_post = get_post($connected_post_id);
    echo "Related post: <a href='" . get_permalink($connected_post) . "'>{$connected_post->post_title}</a>";
}

3. Using Custom Tables

For more complex data structures, you can create a separate table in the database to store relationships.

Steps:

  • Create a table in the database, for example, through register_activation_hook:
global $wpdb;
$table_name = $wpdb->prefix . 'post_relationships';

$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
    id mediumint(9) NOT NULL AUTO_INCREMENT,
    post_id_a mediumint(9) NOT NULL,
    post_id_b mediumint(9) NOT NULL,
    PRIMARY KEY (id)
) $charset_collate;";

require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
  • Insert relationships between posts programmatically:
global $wpdb;
$wpdb->insert(
    $wpdb->prefix . 'post_relationships',
    ['post_id_a' => $post_id_a, 'post_id_b' => $post_id_b]
);
  • Retrieve the related posts for display:
$results = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}post_relationships WHERE post_id_a = $post_id_a");
foreach ($results as $row) {
    $connected_post = get_post($row->post_id_b);
    echo "Related post: <a href='" . get_permalink($connected_post) . "'>{$connected_post->post_title}</a>";
}

4. WP_Query with Taxonomies

If posts can be grouped by categories, you can use taxonomies:

  • Create a custom taxonomy:
function create_custom_taxonomy() {
    register_taxonomy('post_relationship', 'post', [
        'label' => 'Post Relationships',
        'hierarchical' => false,
        'show_ui' => true,
        'show_in_rest' => true,
    ]);
}
add_action('init', 'create_custom_taxonomy');
  • Attach multiple posts to the same taxonomy term.
  • Use WP_Query to fetch related posts:
$related_posts = new WP_Query([
    'post_type' => 'post',
    'tax_query' => [
        [
            'taxonomy' => 'post_relationship',
            'field' => 'term_id',
            'terms' => wp_get_post_terms($post->ID, 'post_relationship', ['fields' => 'ids']),
        ],
    ],
]);

while ($related_posts->have_posts()) {
    $related_posts->the_post();
    echo "<a href='" . get_permalink() . "'>" . get_the_title() . "</a>";
}
wp_reset_postdata();

The choice of approach depends on the complexity of your project. If you need simplicity, plugins are a good option. If you require a custom solution, you can use meta fields or custom tables.

How useful is the publication?

Click on a star to rate it!

Average score 5 / 5. Number of grades: 1

No ratings yet. Rate it first.

Similar posts

How to transfer a site from dle to WordPress?

Transferring a website from DLE (DataLife Engine) to WordPress can be a complex process, especially if the site has a lot of content. Here’s a step-by-step guide: 1. Preparation 2. Export Data from DLE DLE uses its own database structure, so you’ll need to export data and convert it into a format compatible with WordPress:…
Read more