Leap Bun
Leap Bun

Reputation: 2295

How to add a button to a custom post type in Wordpress?

I have a "Products" custom post type. Normally, this custom post type have an "Add New" button. I want to add another button call "Update from Provider".

Currently, I have modify the Wordpress code (in "wordpress\wp-admin\includes\class-wp-list-table.php") to add that button. In this case, when I update Wordpress, my modified code will be deleted. Therefore, I need to move that button to my plug-in code.

In this case, please help me how to move that button to my plug-in code.

enter image description here

Upvotes: 8

Views: 11349

Answers (1)

brasofilo
brasofilo

Reputation: 26065

Well, if you opened the core file you saw that there's no action in it where we can hook.

Only a couple of filters. We can use the following:

add_filter( 'views_edit-movies', 'so_13813805_add_button_to_views' );
function so_13813805_add_button_to_views( $views )
{
    $views['my-button'] = '<button id="update-from-provider" type="button"  title="Update from Provider" style="margin:5px">Update from Provider</button>';
    return $views;
}

It produces this:

custom button in cpt

To put it in an approximate position from where you'd like, use the following:

add_action( 'admin_head-edit.php', 'so_13813805_move_custom_button' );

function so_13813805_move_custom_button(  )
{
    global $current_screen;
    // Not our post type, exit earlier
    if( 'movies' != $current_screen->post_type )
        return;
    ?>
    <script type="text/javascript">
        jQuery(document).ready( function($) 
        {
            $('#update-from-provider').prependTo('span.displaying-num');    
        });     
    </script>
    <?php 
}

Which results in this:
jquery dom manipulation

Upvotes: 18

Related Questions