Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Post ID instead of slug in url for custom post type WordPress

Hello

For the custom post type "listing" I would like the post ID to be displayed in the URL instead of the slug.

Please can you put together a function that I can include in a plugin that will

- Check if the user is viewing "listing" custom post type
- Change the permalink from slug to ID

Thanks
Nick

Answers (3)

2015-01-20

timDesain Nanang answers:

Hi Sir, have you try: [[LINK href="https://wordpress.org/plugins/custom-post-type-permalinks/screenshots/"]]https://wordpress.org/plugins/custom-post-type-permalinks/screenshots/[[/LINK]]

2015-01-20

Ryan S answers:

Hi,

The easiest way is to use the ff.


1.
// check if the current post is listing post-type
if( 'listing' == get_post_type( $post ) )
// your code here

2.
// to give an easy solution is by adding permalinks
e.g. <a href="<?php echo get_permalink(); ?>?listing_id=<?php echo get_the_ID(); ?>"><?php the_title(); ?></a>

so the output would look like this, domain.com/listing/listing-article/?listing_id=1 // so now you can simply get listing_id directly in the permalink above

// another great function you if you wanted to simply assign or get ID from permalink is use this function
url_to_postid( POST PERMALINK );



Hope that helps

2015-01-20

Reigel Gallarde answers:

hi... this should work...


/**
* Plugin Name: Custom permalink for listing post type.
* Plugin URI: http://www.wpquestions.com/question/showChronoLoggedIn/id/10440
* Description: Custom permalink for listing post type
* Author: Reigel Gallarde
* Author URI: http://reigelgallarde.me
* Version: 0.1
* Tested up to: 4.1
*/

add_filter('post_type_link', 'woorei_33551_custom_listing_permalink', 1, 3);
function woorei_33551_custom_listing_permalink($post_link, $post = 0, $leavename) {
if ( $post->post_type == 'listing' ) {
return home_url( '/' . $post->ID);
}
else {
return $post_link;
}
}
add_action( 'init', 'woorei_33551_rewrites_init' );

function woorei_33551_rewrites_init(){
add_rewrite_rule(
'([0-9]+)?$',
'index.php?post_type=listing&p=$matches[1]',
'top' );
}


you can save this as php file then upload to plugins then activate...
or just copy paste to your functions.php file in your current theme.
let me know if you have problem...


Reigel Gallarde comments:

you can look in action here ([[LINK href=" http://printmydesigns.ml/products/"]]product post type[[/LINK]])
you can compare with [[LINK href=" http://printmydesigns.ml/seminars/"]]seminar post type[[/LINK]]