WordPress.org

Ready to get started?Download WordPress

Forums

Call wordpress functions from generated button in wp-admin edit post (7 posts)

  1. drpcken
    Member
    Posted 1 year ago #

    I have a custom post type called PRODUCTS that I'm uploading PDF's to using the wp_upload_bits() function. Mostly because I dont' want to use the Media Library and want to add these PDF's from the PRODUCTS post edit page in the wp-admin. I've created metaboxes for the file upload fields (currently only 2, will add more when I get this working). If there are no meta data for PDF's it will generate a file upload field. If a PDF is already uploaded with metadata it will generate a link to the PDF and a DELETE button next to it. Here's the code for showing my metaboxes:

    function products_pdf_uploads_show_meta() {
    	global $meta_box_pdf_uploads, $post, $prefix;
    
    	echo '<table class="form-table">';
        echo '<p class="description">Upload your PDFs here (DO NOT USE YET.. KENNY DEBUGGING)</p>';
    	foreach ($meta_box_pdf_uploads['fields'] as $field) {		
    
    		//Get current PDF meta
    		$pdf_array = get_post_meta($post->ID, $field['id'], true);
    		//Grab the filename from the end of the path
    		$pdf_filename = substr(strrchr($pdf_array['url'], "/"), 1);
    
    		echo '<tr>',
    				'<td>';
    
    					//If Empty, show file upload dialog
    					if(empty($pdf_array)) {
    						echo '<input type="file" style="width: 700px;" name="', $field['id'], '" id="', $field['id'], '" />';
    
    					} else {  //Else if pdf exists, show link to pdf and add DELETE button
    						echo '<li><a href="' . $pdf_array['url'] . '" target=_blank">'. $pdf_filename . '</a></li>';
    					}
    
    		echo	'</td>',
    				'<td>';
    					//add delete button if PDF is already uploaded
    					if(!empty($pdf_array)) {
    				  		submit_button('Delete', 'delete', 'delete_pdf', false);
    				  	}
    		echo	'</td>',
    			 '</tr>';
    	}
    	echo '</table>';
    
    }

    My question is how can use my generated submit_button to hook into WP functions? Specifically delete_post_meta() and then delete the file from the server?

    Thank you!

  2. bcworkz
    Member
    Posted 1 year ago #

    I've never put a submit button in a meta box, so maybe I'm missing something. I think you want a link, not a submit button, even if you style the link to look like a button. A submit button activates the form's action, which should be to post-new.php, IIRC? It won't know what to do with your button, it'll just store the meta values. In addition, the user may not be ready to submit the whole form when they use your delete button.

    A link can be to your own handler page. It needs to require-once wp-admin.php to access WP functions. To delete a file use the php unlink() function.

  3. drpcken
    Member
    Posted 1 year ago #

    Thank you! I actually already changed it to a link today realizing it would submit the page. Thanks for the heads up! Also thanks for the unlink() function, I didn't realize I could use that and will research it. If I run into any snags I'll update.

    Thank you!

  4. drpcken
    Member
    Posted 1 year ago #

    Aww yes Now i'm getting somewhere, I'm able to trigger an alert() on my link click... thats exciting for me :) Now to just tie it up to the function in my functions.php.
    Thanks for the step in the right direction!

  5. drpcken
    Member
    Posted 1 year ago #

    Ok so here's where I stand. I have a link that I want to hook into wp functions. Code here:

    <a href="#" id="delete-' . $field['id'] . '" class="delete_pdf" title="Delete this PDF." >Delete</a>

    I have jQuery that hooks the click event of that link here:

    jQuery(document).ready(function($) {
    	$('.delete_pdf').each(function(i,e) { //grab the class delete-pdf
    		var id = $(this).attr('id').replace(/delete-/, '');
    		$(this).click(function(){
    			//alert('Clicked! '+ $(this).attr('id'));
    			$.post(wp_ajax.ajaxurl, { action: 'delete_pdf_and_metadata', post_id: id }, function(data){
    				});
    		});
    	});
    
    	function replace_pdf_with_file_upload(){
    		//TODO write to replace PDF link with File Upload
    
    	}
    });

    I tried testing the jQuery accessing my function with a simple `wp_die()' and see if it would show the die screen but it's not working. When I click my link I get nothing, nor do I get errors in my firebug where I'm debugging the jquery.

    Here is my code in my functions.php where I'm registering, enqueueing, and localizing the script, as well as my function I'm trying to access to unlink() the PDF:

    //Add AJAX functionality to post.php to delete files
    add_action('admin_enqueue_scripts', 'my_admin_enqueue_scripts');
    add_action('wp_ajax_delete_meta', 'delete_pdf_and_metadata');
    
    //Add my custom JS to the header of admin
    function my_admin_enqueue_scripts($hook) {
    	global $current_screen;
    
    	if ( 'post.php' != $hook )
    		return;
    	wp_register_script('my-scripts', get_template_directory_uri() . '/js/custom/my-scripts.js' );
    	wp_enqueue_script('my-scripts');
    	wp_localize_script('my-scripts', 'wp_ajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
    }
    
    function delete_pdf_and_metadata() {
    
    	global $post;
    
    	$the_id = intval($_POST['the_id'] );
    	echo $the_id . '<br />';  //debugging
    	//echo $key . '<br />';  //debugging
    	wp_die(print_r($post));   //debuggin
    
    	//delete_post_meta( $post->ID, $key );  //TODO
    }

    I think what is confusing me is in the jQuery here:

    $.post(wp_ajax.ajaxurl, { action: 'delete_pdf_and_metadata', post_id: id }, function(data){ I'm not sure what post_id is suppose to be. Is this passing these values to the wp functions?

  6. drpcken
    Member
    Posted 1 year ago #

    Also am I properly enqueuing and localizing my scripts? This is for admin side only:

    wp_enqueue_script('my-scripts');
    wp_localize_script('my-scripts', 'wp_ajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
  7. bcworkz
    Member
    Posted 1 year ago #

    It's funny what excites us! I'm sure non-coders think we're absolutely mad.

    The enqueue should be OK AFAIK. The localize is wrong because you are not providing data to localize. Do you have data to localize? Maybe you don't need to localize.

    As far a register, I'm pretty sure you need to declare 'jquery' as a dependency of your script. Unfortunately, you've wandered into two subjects I'm really weak on-- jquery and ajax! Even so, I'm pretty sure you can't call a php function from jquery. You must request a php page on the server. That page then calls the function. The page can then return a success or failure depending on the outcome of the function.

    If you don't mind, can we dispense with the ajax aspects for now and focus on getting the link requesting a page that does the delete process? Once that is working correctly, you can easily convert it to ajax.

    So the first step is to correctly build a link that will initiate the delete process. Besides what information needs to be passed back as url parameters to actually find and delete the file, you should also include a nonce so the page receiving the request will know it is a legitimate request and not some fabricated request from a bad actor.

    In a similar vein, the delete function should be constructed so it can only possibly delete pdf files in a certain folder, no matter what sort of request it receives. The page that's requested can reside anywhere as long as it is safe from being deleted during any update. I use either my child theme's folders or my plugin's folder.

    This page first requires once wp-admin.php. This ensures the user is properly logged in. It then gets the url parameters from the request and checks that the nonce is valid. The other parameters are validated, then used to delete the file. Depending on how that goes, a success or failure message is sent back to the user.

    Have fun!

Topic Closed

This topic has been closed to new replies.

About this Topic