0

I've hit a bit of a wall here. I need to take the value of a custom field ("id") and insert it into the URL of a custom post type's page (the CPT is "inventory-item"). The desired outcome is to have the URL structured as "domain.com/cars-for-sale/id/post-name." The "Cars for Sale" component and "Post Name" components are already in place per how I set up the custom post type's permalinks to work. I'm just really struggling with adding this ID segment.

I tried adding the following:

<?php

// Register custom post type
function custom_register_inventory_item_post_type() {
    // Register the custom post type
    register_post_type('inventory-item', array(
        'labels' => array(
            'name' => __('Inventory Items'),
            'singular_name' => __('Inventory Item'),
        ),
        'public' => true,
        'has_archive' => true,
        // Add other necessary arguments
    ));
}
add_action('init', 'custom_register_inventory_item_post_type');

// Add custom rewrite rules
function custom_add_rewrite_rules() {
    add_rewrite_rule('^cars-for-sale/([^/]+)/([^/]+)/?', 'index.php?inventory-item=$matches[2]', 'top');
}
add_action('init', 'custom_add_rewrite_rules');

// Handle query variables
function custom_query_vars($query_vars) {
    $query_vars[] = 'id';
    return $query_vars;
}
add_filter('query_vars', 'custom_query_vars');

// Modify the post permalink
function custom_post_type_permalink($permalink, $post, $leavename) {
    if ($post->post_type == 'inventory-item') {
        $rewritecode = array(
            '%id%',
            '%postname%',
        );
        $id = get_post_meta($post->ID, 'id', true);
        $post_slug = basename(get_permalink($post->ID));
        $rewritereplace = array(
            $id,
            $post_slug,
        );
        $permalink = str_replace($rewritecode, $rewritereplace, $permalink);
    }
    return $permalink;
}
add_filter('post_type_link', 'custom_post_type_permalink', 10, 3);

This just resulted in a 500 error so I removed the code.

2
  • Whenever you're getting a 500, check the log files and they will tell you what the error was... Commented Apr 18, 2024 at 14:14
  • Where do you get '%id%' and '%postname%' from if you don't specify rewrite when registering custom_register_inventory_item_post_type? Commented Apr 18, 2024 at 20:12

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.