3

How can I add a button to a posts -page. (In this case a custom post type).

I'd like to place it next to, or near, the "Add new" button, to import content from a web service.

5

Like this:

function custom_js_to_head() {
    ?>
    <script>
    jQuery(function(){
        jQuery("body.post-type-YOUR-CUSTOM-POST-TYPE .wrap h1").append('<a href="index.php?param=your-action" class="page-title-action">Import from ...</a>');
    });
    </script>
    <?php
}
add_action('admin_head', 'custom_js_to_head');

That code (pasted to functions.php) will dynamically add new link tag after "Add new" link.

  • I was somewhat hoping that the use of javascript wouldn't be necessary. But if there's no hook to add buttons, and it's safe to assume .wrap h1 exists in themes... Then I guess it's acceptable. – Jouni S. Sep 1 '15 at 6:56
  • I dont't know about any hook that can place some HTML exactly on that place. And it's based ond wp-admin HTML structure, so it won't be affected by any front-end theme change. – Marek Sep 1 '15 at 8:13
  • Very weird there is no "Wordpress way" to do that. Or maybe... this is the "Wordpress way"... – Alexandre Bourlier May 25 '17 at 19:31
4

You can add button via add_meta_box function.

function add_your_meta_box(){

add_meta_box('your-metabox-id', 'Title', 'function_of_metabox', 'custom_post_type', 'side', 'high');}

add_action('add_meta_boxes', 'add_your_meta_box'); 

function function_of_metabox()
{?>
    <input type="submit" class="button button-primary button-large" value="Add New" id="add-new"/>
<?php }

if you add to multiple post type, you should use foreach loop.

function add_your_meta_box(){

  $types = array("post","page","custom_post_type");

  foreach($types as $type){

    add_meta_box('your-metabox-id', 'Title', 'function_of_metabox', $type, 'side', 'high');}

}

add_action('add_meta_boxes', 'add_your_meta_box'); 
  • 1
    That solution adds the button on the edit post -page, not the posts listing page, which was what I originally wanted. Could be an OK place to add such a button however. – Jouni S. Sep 1 '15 at 10:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.