I have a custom post type in Wordpress called "tourneys". For reference, here is the code that creates the CPT:
function my_custom_post_tourneys() {
$labels = array(
'name' => __( 'Tourneys', 'post type general name' ),
'singular_name' => __( 'Tourney', 'post type singular name' ),
'add_new' => __( 'Add New', 'tourney' ),
'add_new_item' => __( 'Add New Tourney' ),
'edit_item' => __( 'Edit Tourney' ),
'new_item' => __( 'New Tourney' ),
'all_items' => __( 'All Tourneys' ),
'view_item' => __( 'View Tourney' ),
'search_items' => __( 'Search Tourneys' ),
'not_found' => __( 'No tourneys found' ),
'not_found_in_trash' => __( 'No tourneys found in the Trash' ),
'parent_item_colon' => '',
'menu_name' => 'Tourneys'
);
$args = array(
'labels' => $labels,
'description' => 'Holds our tourneys and tourney specific data',
'rewrite' => array( 'slug' => '' ),
'public' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'show_ui' => true,
'query_var' => true,
'menu_position' => 5,
'capability_type' => 'post',
'hierarchical' => false,
'menu_icon' => 'dashicons-networking',
'supports' => array( 'title', 'author', 'editor', 'thumbnail', 'custom-fields', 'revisions', 'sticky', 'genesis-seo', 'genesis-layouts'),
'has_archive' => true,
);
register_post_type( 'tourneys', $args );
}
add_action( 'init', 'my_custom_post_tourneys' );
The issue I am trying to resolve is that I do not have the "(Edit)" link at the bottom of the CPT on the frontend of Wordpress. I do have the ability to click "Edit Tourney" from the admin menu bar on the front end of the site. However, my client prefers to have the (Edit) link at the bottom of the post content on the frontend.
I understand that this is created with the Wordpress function edit_post_link
. I cannot find a clean way to add this text to every instance of this Custom Post Type. My work around was to create a shortcode and add that shortcode to every CPT post. My shortcode markup does the following:
add_action('loop_end', function () {
edit_post_link(__('(Edit Tourney)'));
}, 99);
This works, but requires me to add this shortcode to every single CPT. I'd prefer a way to build this into the CPT markup by default. I do NOT have a template for this CPT in my child theme.
Any suggestions?
You can use the_content filter hook for this, like so for example:
/**
* Adds an "Edit Tourney" link to the end of the content.
*
* @param string $content The post content.
* @return string $content The (modified) post content.
*/
add_filter('the_content', function ($content) {
if (
is_singular('tourneys') // checks that the link only appears for your CPT
&& in_the_loop()
&& is_main_query()
&& current_user_can('edit_posts')
) {
$edit_link_url = get_edit_post_link( get_the_ID() );
return $content . '<p><a href="' . esc_url( $edit_link_url ) . '">' . __( '(Edit Tourney)' ) . '</a></p>';
}
// ELSE
return $content;
}, 99);