upload image on page using wordpress rest api - wordpress

I want upload image using api on my page so any tell me how i do it?
Now i work with this api
http://localhost/test_project/wp-json/wp/v2/media
but it's doesn't help me for upload image on page or post.
I use wordpress json api plugin.

You can do using following code. Here I have use wp_handle_upload.
$param = array('search' => 'XXXXXXXX');
$imagetype = array(
'bmp' => 'image/bmp',
'gif' => 'image/gif',
'jpe' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'png' => 'image/png',
'tif' => 'image/tiff',
'tiff' => 'image/tiff'
);
$override = array(
'mimes' => $imagetype,
'test_form' => false
);
$upload_file = wp_handle_upload( $_FILES['YOUR_UPLOAD_FILE_NAME'], $override );
remove_filter( 'upload_dir', array($this, 'change_upload_dir') );
if ( isset( $upload['error'] ) ){
// DO ACTION ACCORDINGLY
} else {
// File is uploaded successfully.
$uploaded_file_url = $upload_file['url'];
$uploaded_file_name = basename($upload_file['url']);
}

Related

Custom WooCommerce Gateway

I`m trying to develop a custom payment gateway for WooCommerce plugin, but I have a problem with the checkout page. What I want is to insert a form on the checkout final step page that is submitted automatically after 5 seconds.
My code is:
...
add_action('woocommerce_receipt_' . $this->id, array($this, 'receipt_page'));
add_action('woocommerce_api_wc_' . $this->id, array($this, 'handle_callback'));
}
function handle_callback() {
wp_die('handle_callback');
}
function receipt_page( $order )
{
echo "receipt page";
$this->generate_submit_form_elements( $order );
}
The problem is that "receipt_page" action is not triggered.
Thanks!
oh, its because you forgot to set the has_fields flag to true.
//after setting the id and method_title, set the has_fields to true
$this -> id = 'kiwipay';
$this -> method_title = 'KiwiPay';
$this->has_fields = true; // if you want credit card payment fields to show on the users checkout page
then in the process_payment function put this:
// Payload would look something like this.
$payload = array(
"amount" => $order.get_total(),
"reference" => $order->get_order_number(),
"orderid" => $order->id,
"return_url" => $this->get_return_url($order) //return to thank you page.
);
response = wp_remote_post( $environment_url, array(
'method' => 'POST',
'body' => http_build_query( $payload ),
'timeout' => 90,
'sslverify' => false,
) );
// Retrieve the body's response if no errors found
$response_body = wp_remote_retrieve_body( $response );
$response_headers = wp_remote_retrieve_headers( $response );
//use this if you need to redirect the user to the payment page of the bank.
$querystring = http_build_query( $payload );
return array(
'result' => 'success',
'redirect' => $environment_url . '?' . $querystring,
);

How to delete page after plugin deactivation

I have created page when my plugin is activated. Its working fine. Now i want to delete the page when my plugin is deactivated.
My code is given below :
register_activation_hook( __FILE__, 'my_plugin_install_function');
function my_plugin_install_function() {
$post = array('page_template' => '', 'comment_status' => 'closed', 'ping_status' => 'closed' ,'post_author' => 1,'post_date' => date('Y-m-d H:i:s'),'post_name' => 'Checklists','post_status' => 'publish' ,
'post_title' => 'Checklists',
'post_type' => 'page',
);//insert page and save the id
$newvalue = wp_insert_post( $post, false );
//save the id in the database
update_option( 'hclpage', $newvalue ); }
register_deactivation_hook( __FILE__, 'my_plugin_remove' );
function my_plugin_remove() {// the id of our page...
$the_page_id = get_option( $newvalue );
if( $the_page_id ) {
wp_delete_post( $the_page_id ); // this will trash, not delete
}
How can I get the post id to delete the page?
wp_delete_post( $the_page_id, true );
The second parameter is to "force deletion", is boolean, and when set to true it deletes the post without trashing it.
You can read more in the docs
You can get the ID using the get_option function:
get_option('hclpage');

How do you target a specific page in Wordpress functions.php?

I am currently using the Multi Post Thumbnails plugin for Wordpress, but I only want the extra thumbnails provided by the plugin to show on one specific page. The plugin does not appear to natively support this functionality but it seems like something that would be pretty easy to add, I'm just not sure of the right way to go about it as I'm fairly new to Wordpress development.
The code for Multi Post Thumbnails is the following, which simply goes in functions.php:
if (class_exists('MultiPostThumbnails')) {
new MultiPostThumbnails(
array(
'label' => 'Secondary Image',
'id' => 'secondary-image',
'post_type' => 'page'
)
);
new MultiPostThumbnails(
array(
'label' => 'Tertiary Image',
'id' => 'tertiary-image',
'post_type' => 'page'
)
);
}
It seems to me it would just be a simple case of wrapping this in a check so that it only runs for a specific page ID, but I'm not quite sure how to go about doing that.
This is probably somewhat of a hack. To my knowledge post/page id's are not accessible from inside functions.php.
// get the id of the post/page based on the request uri.
$url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$post_id = url_to_postid($url);
// the id of the specific page/post.
$specific_post_id = 3;
// check if the requested post id is identical to the specific post id.
if ($post_id == $specific_post_id) {
if (class_exists('MultiPostThumbnails')) {
new MultiPostThumbnails(
array(
'label' => 'Secondary Image',
'id' => 'secondary-image',
'post_type' => 'page'
)
);
new MultiPostThumbnails(
array(
'label' => 'Tertiary Image',
'id' => 'tertiary-image',
'post_type' => 'page'
)
);
}
}
This is also probably a hack but it worked for me. I got stung by the AJAX 'post_id' back to the admin page once the image has been selected. My usage was for a slug but the function could easily be modified for a post ID.
function is_admin_edit_page( $slug ){
if( ( isset($_GET) && isset($_GET['post']) ) || ( isset($_POST) && isset($_POST['post_id']) ) )
{
$post_id = 0;
if(isset($_GET) && isset($_GET['post']))
{
$post_id = $_GET['post'];
}
else if(isset($_POST) && isset($_POST['post_id']))
{
$post_id = $_POST['post_id'];
}
if($post_id != 0)
{
$c_post = get_post($post_id);
if( $c_post->post_name == $slug )
{
return true;
}
}
}
return false;
}
if( is_admin_edit_page('work') ) {
new MultiPostThumbnails(
array(
'label' => 'Hero 1 (2048px x 756px JPEG)',
'id' => 'am-hero-1',
'post_type' => 'page'
)
);
}

Wrong URL when using wp_insert_attachment

I created a plugin as 3rd party to acomodate system with wordpress website on main site. So the scenario is:
when user hit submit on the system it will also added to wordpress website, it's working perfect, no problem at all. but when i try to set the featured image through wp_insert_attachment it keep me give a URL like
http://xxxxx.com/wp-content/uploads/http://xxxxx.com/system/media/.../xx.jpg
what i want to be is only http://xxxxx.com/system/media/.../xx.jpg saved as featured image, is it possible to do so?
here is my current script
if($pt == "pictures"){
$filename_url = $_GET["dml_file"];
$mime = wp_check_filetype($filename_url, null);
$data = array(
'post_mime_type' => $mime['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($_GET["dml_file"])),
'post_content' => '',
'post_status' => 'inherit'
);
$attachment_id = wp_insert_attachment($data, $filename_url, $pid);
update_post_meta($pid, $custom_field, $attachment_id);
}else{
update_post_meta($pid, $custom_field, $_GET["dml_file"]);
}
I have tried to use file_get_contents and file_put_contents to create image in WP installation, but I don't want that way.
The system is submitting this:
http://user:pass!#localhost/wp-content/plugins/dml3rdparty/dmlsubmit.php?dml_sa‌ve=save&dml_file=http://xxx.xxx.xxx.xxx/dml/assets/media/Accreditation/download.d‌15bdf4e9e.jpg&dml_type=Print Quality Photos&dml_description=test|download.jpg&dml_status=publish
From wp_insert_attachment documentation (my emphasis in bold):
$filename
(string) (optional) Location of the file on the server. Use absolute path and not the URI of the file. The file MUST be on the uploads directory. See wp_upload_dir()
Default: false
Much probably, you can solve this with media_handle_sideload().
This function gets the file content using cURL:
function my_file_get_contents($url){
$options = array(
CURLOPT_AUTOREFERER => true,
CURLOPT_HEADER => false,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_CONNECTTIMEOUT => 120,
CURLOPT_TIMEOUT => 120,
CURLOPT_MAXREDIRS => 10
);
$ch = curl_init($url);
curl_setopt_array($ch,$options);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
This function uses the above to get the image, saves it to the uploads folder, and sets it as a featured image for a post:
function my_featured_image($image_url,$post_id){
$upload_dir = wp_upload_dir();
$image_data = my_file_get_contents($image_url);
$filename = strtok($image_url, '?');
$filename = basename($filename);
if(wp_mkdir_p($upload_dir["path"])){
$file = $upload_dir["path"]."/".$filename;
}else{
$file = $upload_dir["basedir"]."/".$filename;
}
file_put_contents($file, $image_data);
$wp_filetype = wp_check_filetype($filename,null);
$post_author = get_post_field("post_author",$post_id);
$attachment = array(
"post_author" => $post_author,
"post_mime_type" => $wp_filetype["type"],
"post_title" => sanitize_file_name($filename),
"post_content" => "",
"post_status" => "inherit"
);
$attach_id = wp_insert_attachment($attachment,$file,$post_id);
require_once(ABSPATH."wp-admin/includes/image.php");
$attach_data = wp_generate_attachment_metadata($attach_id,$file);
$res1 = wp_update_attachment_metadata($attach_id,$attach_data);
$res2 = set_post_thumbnail($post_id, $attach_id);
}
Call with:
my_featured_image($image_url,$post_id);

wordpress custom post types - broken publish button

I created a gallery post type (as part of a plugin) that contains besides a title and some meta information also a wp_list_table that queries those attachments which have the current post as post_parent. I ran into a problem when suddenly my publish button stopped working. No matter if I'm creating a new gallery or if I'm editing an old one, once I click on update/publish my changes get lost and I end up on edit.php.
Anybody knows what that's all about?
I where able to figure out where the problem seems to be. It's in my list_table class which inherits from wp_list_table. after commenting out some unimportant functions i ended up with a different error but still no new or updated gallery. Now I get the are you sure you want to do this page.
Even the most basic class won't work...
if( ! class_exists( 'WP_List_Table' ) ) {
require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}
class Yard_Attachment_Table extends WP_List_Table {
function __construct() {
global $status, $page;
parent::__construct( array(
'singular' => 'yard Attachment',
'plural' => 'yard Attachments',
'ajax' => false
) );
}
function column_default($item, $column_name) {
return 'default';
}
function get_columns(){
$columns = array(
'checkbox' => '<input type="checkbox" />', //for simplicity its not 'cb'
'thumb' => 'Thumbnail',
'title' => 'Titel',
'pos' => 'Position'
);
return $columns;
}
function prepare_items() {
global $wpdb;
$columns = $this->get_columns();
$hidden = array();
$sortable = $this->get_sortable_columns();
$this->_column_headers = array($columns, $hidden, $sortable);
if (isset($_REQUEST['post'])) {
$query = " SELECT *
FROM $wpdb->posts
WHERE post_type = 'attachment'
AND post_parent = {$_REQUEST['post']}";
$data = $wpdb->get_results($query, ARRAY_A);
} else {
$data = array();
}
$this->items = $data;
}
}
In the plugin class' constructor I use
add_action('add_meta_boxes_yard_gallery', array($this, 'yard_metaboxes'));.
In yard_metaboxes I use add_meta_box and in the function I have as a callback i'm creating a new instance of my table class and I call prepare_items() and display()
Turning error_reporting on my page dies with these messages:
Strict Standards: Only variables should be passed by reference in /Applications/MAMP/htdocs/Web/ChristophRokitta/wp v.1.0/wp-includes/pomo/mo.php on line 210
Warning: Cannot modify header information - headers already sent by (output started at /Applications/MAMP/htdocs/Web/ChristophRokitta/wp v.1.0/wp-includes/pomo/mo.php:210) in /Applications/MAMP/htdocs/Web/ChristophRokitta/wp v.1.0/wp-includes/pluggable.php on line 876
BTW I'm not localizing.
Please help! If i had more reputation I'd offer it.
Adding the meta box code
in my plugin file:
require_once( plugin_dir_path( __FILE__ ) . 'class-yard.php' );
Yard::get_instance();
in my class-yard file the meta box methods are at the bottom:
class Yard {
protected static $instance = null;
private function __construct() {
include_once('class-yard-attachments.php');
add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_styles' ) );
add_action('after_setup_theme', array($this, 'yard_thumbnails'));
add_action('init', array($this, 'yard_post_type'));
add_action('init', array($this, 'yard_taxonomies'));
add_filter('manage_yard_gallery_posts_columns', array($this, 'yard_add_columns'));
add_action('manage_posts_custom_column', array($this, 'yard_fill_columns'));
add_action('add_meta_boxes_yard_gallery', array($this, 'yard_metaboxes'));
}
public static function get_instance() {// If the single instance hasn't been set, set it now.
if (null == self::$instance ) {
self::$instance = new self;
}
return self::$instance;
}
public function enqueue_admin_styles() {
$screen = get_current_screen();
if ($screen->post_type == 'yard_gallery') {
wp_register_style( 'yard-gallery-style', plugins_url('css/yard-gallery-style.css', __FILE__) );
wp_enqueue_style( 'yard-gallery-style' );
}
}
public function yard_thumbnails() {
//add_image_size('yard-thumbnail', 100, 100, true);
}
public function yard_post_type() {
$gallery_labels = array(
'name' => 'Galerien',
'singular_name' => 'Galerie',
'all_items' => 'Alle Galerien',
'add_new' => 'Erstellen',
'add_new_item' => 'Neue Galerie erstellen',
'edit_item' => 'Galerie bearbeiten',
'new_item' => 'Neue Galerie',
'view' => 'Galerie anzeigen',
'view_item' => 'Gallerie anzeigen',
'search_items' => 'Galerie durchsuchen',
'not_found' => 'Keine Galerien gefunden',
'not_found_in_trash' => 'Es befinden sich keine Galerien im Papierkorb',
'parent_item_colon' => ''
);
$gallery_args = array(
'labels' => $gallery_labels,
'public' => true,
// 'publicly_queryable' => true,
// 'show_ui' => true,
// 'show_in_menu' => true,
// 'query_var' => true,
'rewrite' => true,
// 'capability_type' => 'post',
// 'hierarchical' => false,
'menu_position' => 12,
'supports' => array(
'title'
)
// 'menu_icon' => plugin_dir_url(__FILE__) . '/assets/icon_16_grey.png'//16x16 png if you want an icon
);
register_post_type('yard_gallery', $gallery_args);
}
public function yard_taxonomies() {
register_taxonomy(
'yard_work_type',
'yard_gallery',
array(
'hierarchical' => true,
'label' => 'Art der Arbeit'
)
);
register_taxonomy(
'yard_subject',
'yard_gallery',
array(
'hierarchical' => true,
'label' => 'Motiv'
)
);
}
public function yard_add_columns( $columns ){
$columns = array(
'cb' => '<input type="checkbox">',
'yard_post_thumb' => 'Thumbnail',
'title' => 'Bezeichnung',
'yard_pos' => 'Position',
'date' => 'Datum'
);
return $columns;
}
public function yard_fill_columns( $column ) {
global $post;
switch ($column) {
case 'yard_post_thumb' :
echo the_post_thumbnail('admin-list-thumb');
break;
}
}
public function yard_metaboxes( $post ) {
global $wp_meta_boxes;
add_meta_box(
'yard-attachments',
'Bilder',
array($this, 'get_yard_attachment_table'),
'yard_gallery'
);
}
public function get_yard_attachment_table() {
$yard_list_table = new Yard_Attachment_Table();
$yard_list_table->prepare_items();
$yard_list_table->display();
}
}
Strict Standards: Only variables should be passed by reference in /Applications/MAMP/htdocs/Web/ChristophRokitta/wp v.1.0/wp-includes/pomo/mo.php on line 210
The error message tells it all. The ".../popo/mo.php" file has to do with (is related to) the Wordpress translation. (I bet you're using Wordpress with German language files).
I can't see what could be wrong in the code you've posted here, but something is interfering with translation. Looking at what the error message tells us, some variable that Wordpress tries to translate fails to be translated since it's not the correct type.
Warning: Cannot modify header information - headers already sent by (output started at /Applications/MAMP/htdocs/Web/ChristophRokitta/wp v.1.0/wp-includes/pomo/mo.php:210) in /Applications/MAMP/htdocs/Web/ChristophRokitta/wp v.1.0/wp-includes/pluggable.php on line 876
This is a logic result of the previous error message and the headers Wordpress tries to send to the browser.
What's happening: the first error message is being pushed to the client and flushed to the browser screen. Next, Wordpress tries to send it's usual headers and produces an error while doing so because headers have to be send before ANY content is being send to the client.
In other words: the "Cannot modify header information" error always comes up when you echo something to screen and then try to send "header(...)" information. In this case, the translation problem produces the first error message and then Wordpress tries to send headers, which fails and produces the second error message.
TIPS
Check everything you're doing which is related to translation (read: wherever you are passing "German" and/or "English" language strings)
and even more important
Make sure that you're actually passing the correct type(s)... looking at the error and your code, it could well be you're passing a class, a class reference, or another object somewhere instead of the expected variable.

Resources