I'm trying to update remote woocommerce product but i'm stucked. How can we complete this code:
class myDemo {
public function __construct() {
$this->url = 'http://localhost/alfa/wp-json/wc/v2/products/2213';
$this->meta_key = 'whatever';
$this->consumer_key = 'ck_5978846499ea9bb1554b420e59072e46b8dedb1d';
$this->consumer_secret = 'cs_1009590c5443306f2082b2e508098be37fba2ee5';
$this->access_token = '';
$this->access_token_secret = '';
$this->method = 'PUT';
$this->set_signature_key();
$this->set_nonce();
$this->set_headers();
$this->set_base_string();
$this->set_signature();
$this->set_headers();
$this->set_header_string();
}
function get_response() {
$url = $this->url;
if( ! empty( $this->meta_key ) ) {
$url = add_query_arg( array( 'meta_key' => $this->meta_key ), $url );
}
$args = array(
'method' => $this->method,
'headers' => array(
'Authorization' => 'OAuth ' . $this->header_string,
),
);
$out = wp_remote_request( $url, $args );
return $out;
}
function set_signature_key() {
$this->signature_key = urlencode( $this->consumer_secret ) . '&' . urlencode( $this->access_token_secret );
}
function set_nonce() {
$this->nonce = wp_create_nonce( rand() . $this->url . $this->method );
}
function set_headers() {
if( ! isset( $this->headers ) ) {
$this->headers = array(
'oauth_consumer_key' => $this->consumer_key,
'oauth_nonce' => $this->nonce,
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => time(),
'oauth_token' => $this->access_token,
'oauth_version' => '1.0',
);
} elseif( isset( $this->signature ) ) {
$this->headers['oauth_signature'] = $this->signature;
}
}
function set_base_string() {
$headers = $this->headers;
$url_params = array(
'meta_key' => $this->meta_key
);
$headers_and_params = array_merge( $headers, $url_params );
ksort( $headers_and_params );
$headers_and_params_string = '';
foreach( $headers_and_params as $key => $value ) {
$headers_and_params_string .= "$key=$value&";
}
$headers_and_params_string = rtrim( $headers_and_params_string, '&' );
$out = $this->method . '&' . rawurlencode( $this->url ) . '&' . rawurlencode( $headers_and_params_string );
$this->base_string = $out;
}
function set_signature() {
$out = hash_hmac( 'sha1', $this->base_string, $this->signature_key, TRUE );
$out = base64_encode( $out );
$this->signature = $out;
}
function set_header_string() {
// Will hold the combined string of headers.
$out = '';
foreach( $this->headers as $key => $value ) {
$value = rawurlencode( $value );
$out .= $key . '=' . '"' . $value . '"' . ', ';
}
$out = rtrim( $out, ', ' );
$this->header_string = $out;
}
}
$demo = new myDemo();
die(json_encode($demo->get_response()));
I'm interesting with that:
https://woocommerce.github.io/woocommerce-rest-api-docs/?php#update-a-product
I saw this code part:
$data = [
'regular_price' => '24.54'
];
I must send this data array to remote woocommerce. But i don't know how.
Thanks for everything.
Related
woocommerce order page in, I want to filter orders by vendor. I am using the wcfm marketplace plugin.
Vendor name appears here. but when I filter, the orders are not listed.
please help :(woocommerce order page
function wcmp_admin_filter_by_vendor() {
global $typenow;
if ($typenow == 'shop_order') {
$admin_dd_html = '<select name="admin_order_vendor" id="dropdown_admin_order_vendor"><option value="">'.__("Show All Vendors", "dc-woocommerce-multi-vendor").'</option>';
$vendors = get_wcmp_vendors();
if($vendors) :
foreach ($vendors as $vendor) {
$admin_dd_html .= '<option value="'.$vendor->term_id.'">'.$vendor->page_title.'</option>';
}
endif;
$admin_dd_html .= '</select>';
echo $admin_dd_html;
}
}
add_action( 'restrict_manage_posts', 'wcmp_admin_filter_by_vendor');
function get_vendor_parent_order($id) {
$vendor_orders = get_posts( array(
'numberposts' => -1,
'meta_key' => '_vendor_id',
'meta_value' => $id,
'post_type' => 'shop_order',
'post_status' => 'any',
) );
foreach( $vendor_orders as $vendor_order ) {
$parent_order = wp_get_post_parent_id( $vendor_order->ID );
$parent_orders[] = $parent_order;
}
return $parent_orders;
}
function filter_orders_by_vendor_in_admin_dashboard( $query ) {
if (current_user_can('administrator') && !empty($_REQUEST['admin_order_vendor'])) {
$vendor_term_id = isset($_GET['admin_order_vendor'])?$_GET['admin_order_vendor']:'';
$vendor = get_wcmp_vendor_by_term($vendor_term_id);
$parent_orders = get_vendor_parent_order($vendor->id);
$query['post__in'] = $parent_orders;
return $query;
}
return $query;
}
add_filter( 'wcmp_shop_order_query_request', 'filter_orders_by_vendor_in_admin_dashboard');
function remove_wcmp_order_hook() {
global $WCMp;
remove_action( 'manage_shop_order_posts_custom_column', array($WCMp->order, 'wcmp_show_shop_order_columns'), 99, 2 );
}
add_action('init', 'remove_wcmp_order_hook');
function wcmp_show_shop_order_columns($column, $post_id) {
global $WCMp;
switch ($column) {
case 'wcmp_suborder' :
$wcmp_suborders = $WCMp->order->get_suborders($post_id);
if ($wcmp_suborders) {
echo '<ul class="wcmp-order-vendor" style="margin:0px;">';
foreach ($wcmp_suborders as $suborder) {
$vendor = get_wcmp_vendor(get_post_field('post_author', $suborder->get_id()));
$vendor->ID = get_post_field('post_author', $suborder->get_id());
$vendor_term_id = isset($_GET['admin_order_vendor'])?$_GET['admin_order_vendor']:'';
$filter_vendor = get_wcmp_vendor_by_term($vendor_term_id);
$filter_vendor_id = isset($filter_vendor->id)?$filter_vendor->id:'';
if( $vendor->ID == $filter_vendor_id || $filter_vendor_id == '' ) {
$order_uri = apply_filters('wcmp_admin_vendor_shop_order_edit_url', esc_url('post.php?post=' . $suborder->get_id() . '&action=edit'), $suborder->get_id());
printf('<li><mark class="%s tips" data-tip="%s">%s</mark> <strong>#%s</strong> – <small class="wcmp-order-for-vendor">%s %s</small></li>', sanitize_title($suborder->get_status()), $suborder->get_status(), $suborder->get_status(), $order_uri, $suborder->get_order_number(), _x('for', 'Order table details', 'dc-woocommerce-multi-vendor'), $vendor->page_title
);
}
do_action('wcmp_after_suborder_details', $suborder);
}
echo '<ul>';
} else {
echo '<span class="na">–</span>';
}
break;
}
}
add_action('manage_shop_order_posts_custom_column', 'wcmp_show_shop_order_columns', 99, 2);
My WordPress page shows shortcodes like [vc_row][vc_column][vc_column_text] .
Help me identify the root cause.
I have migrated the wordpress sql files from one host to another.
You could modify this Utility Script Runner script to remove shortcodes that no longer exist but are in your page content. Definitely do this on staging before you do it on live. high likelyhood of wrecking up the place. This script has been sitting for close to a year and I honestly can't remember if any of it doesn't work as expected. test a lot on staging before running this on anything you really care about.
<?php if(!defined('ABSPATH')) { die(); }
/**
* Utility Name: Remove and Flatten Shortcodes
* Description: Strip Shortcodes from all posts, with several processing options
* Supports: input
* Version: 0.0.2
**/
if (!class_exists('StripShortcodes')) {
class StripShortcodes {
var $wrappers = array(),
$swaps = array();
public static function Instance() {
static $instance = null;
if ($instance === null) {
$instance = new self();
}
return $instance;
}
public function __construct() {
add_filter('wp_util_script', array($this, 'strip_shortcodes_run'), 10, 3);
add_filter('wp_util_input_html', array($this, 'strip_shortcodes_input_html'));
}
public function strip_shortcodes_input_html( $html ) {
global $shortcode_tags;
$post_types = get_post_types( array(
'exclude_from_search' => false
), 'names' );
$post_types = array_diff( $post_types, array( 'revision', 'attachment' ) );
?>
<p>
<strong>WARNING! DO NOT RUN THIS ON A LIVE SITE!</strong><br>
This utility may cause data loss. Even restoring a backup may wipe out any changes since the last run of this utility.
</p>
<label>
<input type="checkbox" name="restore" value="restore"/>
<span>Restore From Backup</span>
</label>
<label>
<span>Post Types to Process</span>
<select name="post_types[]" multiple="multiple">
<option value="none" selected="selected">none</option>
<option value="any">all</option>
<?php
foreach( $post_types as $post_type ) {
echo '<option value="' . esc_attr( $post_type ) . '">' . $post_type . '</option>';
}
?>
</select>
</label>
<hr/>
<p>
Select what you would like to do with each shortcode.
</p>
<?php
if( !empty( $shortcode_tags ) ) {
foreach( $shortcode_tags as $tag => $callable ) {
?>
<div class="shortcode-options-wrapper">
<label>
<span>[<?php echo $tag; ?>]</span>
<select class="shortcode-select" name="shortcodes[<?php echo esc_attr( $tag ); ?>]"/>
<option value="skip">Skip (do not process)</option>
<option value="strip">Remove (deletes shortcode content)</option>
<option value="unwrap">Unwrap Content</option>
<option value="parse">Flatten (parses to HTML)</option>
<option value="swap">Swap (Replace with another shortcode)</option>
</select>
</label>
</div>
<?php
}
}
echo $this->build_form_script();
return ob_get_clean();
}
private function build_form_script () {
global $shortcode_tags;
ob_start(); ?>
<script type="text/javascript">
(jQuery)(function($) {
'use strict';
var unwrap = '<div class="wrap-wrapper"><p>Wrapper for content (use "sprintf()" formatting, including the %s for the content)</p><label>Wrapper<input class="shortcode-wrap"></label></div>';
var swap = '<div class="swap-wrapper"><select class="shortcode-swap"><?php foreach ($shortcode_tags as $tag => $callable) { echo '<option value="' . $tag . '">' . esc_attr($tag) . '</option>'; }?></select></div>'
$(document).on('change', '.shortcode-select', function () {
var $this = $(this);
var name = $this.attr('name');
if ($this.val() == 'unwrap') {
$this.closest('.shortcode-options-wrapper').append(unwrap);
$this.closest('.shortcode-options-wrapper').find('.shortcode-wrap').attr('name', 'wrap_' + name);
$this.closest('.shortcode-options-wrapper').find('.swap-wrapper').remove();
}
else if ($this.val() == 'swap') {
$this.closest('.shortcode-options-wrapper').append(swap);
$this.closest('.shortcode-options-wrapper').find('.shortcode-swap').attr('name', 'swap_' + name);
$this.closest('.shortcode-options-wrapper').find('.wrap-wrapper').remove();
} else {
$this.closest('.shortcode-options-wrapper').find('.wrap-wrapper').remove();
$this.closest('.shortcode-options-wrapper').find('.swap-wrapper').remove();
}
})
});
</script>
<?php return ob_get_clean();
}
public function strip_shortcodes_run( $legacy, $state, $atts ) {
$batch = 10;
$offset = 0;
if( !empty( $state['offset'] ) ) {
$offset = $state['offset'];
}
$result = array(
'state' => 'error',
'message' => 'an unknown error has occurred',
);
$post_types = 'none';
if( !empty( $atts['post_types'] ) && !in_array( 'none', $atts['post_types'] ) ) {
$post_types = $atts['post_types'];
}
$shortcode_settings = array();
if( !empty( $atts['shortcodes'] ) ) {
$shortcode_settings['core'] = $atts['shortcodes'];
$shortcode_settings['wrap'] = $atts['wrap_shortcodes'];
$shortcode_settings['swap'] = $atts['swap_shortcodes'];
}
$restore = true;
if( empty( $atts['restore'] ) ) {
$this->replace_shortcode_functions( $shortcode_settings );
$restore = false;
}
$query = new WP_Query( array(
'posts_per_page' => $batch,
'offset' => $offset,
'post_type' => $post_types
) );
if( !$query->have_posts() ) {
$result = array(
'state' => 'complete',
'message' => 'successfully processed all posts'
);
} else {
$offset += $query->post_count;
while( $query->have_posts() ) {
$query->the_post();
$post = get_post();
$backup = get_post_meta( $post->ID, 'flatten_shortcodes_backup', true );
if( $restore ) {
if( $backup ) {
$post->post_content = $backup;
wp_update_post( $post );
delete_post_meta( $post->ID, 'flatten_shortcodes_backup' );
}
} else {
if( !$backup ) {
update_post_meta( $post->ID, 'flatten_shortcodes_backup', $post->post_content );
}
$post->post_content = do_shortcode( $post->post_content );
wp_update_post( $post );
}
}
$result = array(
'state' => array(
'offset' => $offset
),
'message' => $offset . ' posts processed'
);
}
return $result;
}
private function replace_shortcode_functions( $settings = array() ) {
global $shortcode_tags;
foreach( $shortcode_tags as $tag => $callable ) {
$setting = 'skip';
if( !empty( $settings['core'][$tag] ) ) {
$setting = $settings['core'][$tag];
}
switch( $setting ) {
case 'strip' :
$shortcode_tags[$tag] = "__return_empty_string";
break;
case 'unwrap':
$shortcode_tags[$tag] = array($this, 'replace_shortcode_unwrap');
$this->wrappers[$tag] = $settings['wrap'][$tag];
break;
case 'parse' :
// nothing needed
break;
case 'swap' :
$shortcode_tags[$tag] = array($this, 'swap_shortcode');
$this->swaps[$tag] = $settings['swap'][$tag];
break;
case 'skip' :
default :
unset( $shortcode_tags[$tag] );
}
}
}
public function replace_shortcode_unwrap( $atts=array(), $content='', $tag ) {
return sprintf($this->wrappers[$tag], $content);
}
public function swap_shortcode( $atts=array(), $content='', $tag ) {
$attString = '';
$newTag = $this->swaps[$tag];
if (!empty($atts)) {
foreach ($atts as $key => $att) {
$attString .= ' ' . $key . '="' . $att . '"';
}
}
$output = '[' . $newTag . $attString . ']';
if ($content) {
$output .= $content . '[/' . $newTag . ']';
}
return $output;
}
}
StripShortcodes::Instance();
}
I have got same result. My theme is wp baker. I activated edge core plugin and other required plug ins and it was solved.
I want to load my post category in the drop-down select box
how I do this
help me please I am new to programming:
this is my code that creates the custom meta boxes and now in the category boxenter image description here, I want that it loads all the category of post in the drop-down menu: the output of the code is shown in the image attached
<?php
//Start: Adding custom metaboxes
class leaderboarddetailMetabox {
private $screen = array(
'ld-leaderboard',
);
private $meta_fields = array(
array(
'label' => 'Number of Students',
'id' => 'numberofstudent_81418',
'type' => 'number',
),
array(
'label' => 'Select Point Type',
'id' => 'selectpointtype_39141',
'type' => 'select',
'options' => array(
'Select',
'Int',
'Float',
'String',
),
),
array(
'label' => 'Category',
'id' => 'category_59112',
'type' => 'select',
'options' => array(
'Select',
'Course',
'Lesson',
'Topic',
'Quiz',
'Category',
),
),
array(
'label' => 'Time',
'id' => 'time_93126',
'type' => 'date',
),
array(
'label' => 'Shortcode',
'id' => 'shortcode_85946',
'type' => 'text',
'readonly' => true,
),
);
public function __construct() {
add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ) );
add_action( 'save_post', array( $this, 'save_fields' ) );
}
// show meta boxes on admin page
public function add_meta_boxes() {
foreach ( $this->screen as $single_screen ) {
add_meta_box(
'leaderboarddetail',
__( 'leader board detail', 'textdomain' ),
array( $this, 'meta_box_callback' ),
$single_screen,
'advanced',
'default'
);
}
}
public function meta_box_callback( $post ) {
wp_nonce_field( 'leaderboarddetail_data', 'leaderboarddetail_nonce' );
$this->field_generator( $post );
}
public function field_generator( $post ) {
$output = '';
foreach ( $this->meta_fields as $meta_field ) {
$label = '<label for="' . $meta_field['id'] . '">' . $meta_field['label'] . '</label>';
$meta_value = get_post_meta( $post->ID, $meta_field['id'], true );
if ( empty( $meta_value ) ) {
$meta_value = $meta_field['default']; }
switch ( $meta_field['type'] ) {
case 'select':
$input = sprintf(
'<select id="%s" name="%s">',
$meta_field['id'],
$meta_field['id']
);
foreach ( $meta_field['options'] as $key => $value ) {
$meta_field_value = !is_numeric( $key ) ? $key : $value;
$input .= sprintf(
'<option %s value="%s">%s</option>',
$meta_value === $meta_field_value ? 'selected' : '',
$meta_field_value,
$value
);
}
$input .= '</select>';
break;
default:
$input = sprintf(
'<input %s id="%s" name="%s" type="%s" value="%s" %s >',
$meta_field['type'] !== 'color' ? 'style="width: 100%"' : '',
$meta_field['id'],
$meta_field['id'],
$meta_field['type'],
$meta_value,
$meta_field['readonly'] ? "readonly" : ""
);
}
$output .= $this->format_rows( $label, $input );
}
echo '<table class="form-table"><tbody>' . $output . '</tbody></table>';
}
public function format_rows( $label, $input ) {
return '<tr><th>'.$label.'</th><td>'.$input.'</td></tr>';
}
// save custom field data to databse and in the field
public function save_fields( $post_id ) {
if ( ! isset( $_POST['leaderboarddetail_nonce'] ) )
return $post_id;
$nonce = $_POST['leaderboarddetail_nonce'];
if ( !wp_verify_nonce( $nonce, 'leaderboarddetail_data' ) )
return $post_id;
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return $post_id;
foreach ( $this->meta_fields as $meta_field ) {
if ( isset( $_POST[ $meta_field['id'] ] ) ) {
switch ( $meta_field['type'] ) {
case 'email':
$_POST[ $meta_field['id'] ] = sanitize_email( $_POST[ $meta_field['id'] ] );
break;
case 'text':
$_POST[ $meta_field['id'] ] = sanitize_text_field( $_POST[ $meta_field['id'] ] );
break;
}
update_post_meta( $post_id, $meta_field['id'], $_POST[ $meta_field['id'] ] );
} else if ( $meta_field['type'] === 'checkbox' ) {
update_post_meta( $post_id, $meta_field['id'], '0' );
}
// generate shortcode and save
if( $meta_field['id'] == 'shortcode_85946' ) {
// update meta
update_post_meta( $post_id, $meta_field['id'], "[custom-shortcode id=" . $post_id . "]");
}
}
}
}
if (class_exists('leaderboarddetailMetabox')) {
new leaderboarddetailMetabox;
};
?>
/**
* Class PayPal
* #package Bookly\Lib\Payment
*/
class PayPal
{
// Array for cleaning PayPal request
static public $remove_parameters = array( 'action', 'token', 'PayerID', 'ab_fid', 'error_msg', 'type' );
/**
* The array of products for checkout
*
* #var array
*/
protected $products = array();
/**
* Send the Express Checkout NVP request
*
* #param $form_id
* #throws \Exception
*/
public function send_EC_Request( $form_id )
{
if ( !session_id() ) {
#session_start();
}
if ( ! count( $this->products ) ) {
throw new \Exception( 'Products not found!' );
}
$total = 0;
// create the data to send on PayPal
$data = array(
'SOLUTIONTYPE' => 'Sole',
'PAYMENTREQUEST_0_PAYMENTACTION' => 'Sale',
'PAYMENTREQUEST_0_CURRENCYCODE' => get_option( 'ab_currency' ),
'NOSHIPPING' => 1,
'RETURNURL' => add_query_arg( array( 'action' => 'ab-paypal-return', 'ab_fid' => $form_id ), Lib\Utils\Common::getCurrentPageURL() ),
'CANCELURL' => add_query_arg( array( 'action' => 'ab-paypal-cancel', 'ab_fid' => $form_id ), Lib\Utils\Common::getCurrentPageURL() )
);
foreach ( $this->products as $index => $product ) {
$data[ 'L_PAYMENTREQUEST_0_NAME' . $index ] = $product->name;
$data[ 'L_PAYMENTREQUEST_0_AMT' . $index ] = $product->price;
$data[ 'L_PAYMENTREQUEST_0_QTY' . $index ] = $product->qty;
$total += ( $product->qty * $product->price );
}
$data['PAYMENTREQUEST_0_AMT'] = $total;
$data['PAYMENTREQUEST_0_ITEMAMT'] = $total;
echo "<pre>";
print_r($data);
exit;
// send the request to PayPal
$response = self::sendNvpRequest( 'SetExpressCheckout', $data );
// Respond according to message we receive from PayPal
if ( 'SUCCESS' == strtoupper( $response['ACK'] ) || 'SUCCESSWITHWARNING' == strtoupper( $response['ACK'] ) ) {
//$paypalurl = 'https://www' . get_option( 'ab_paypal_ec_mode' ) . '.paypal.com/cgi-bin/webscr?cmd=_express-checkout&useraction=commit&token=' . urldecode( $response['TOKEN'] );
$paypalurl = 'https://www' . get_option( 'ab_paypal_ec_mode' ) . '.paypal.com/cgi-bin/webscr?cmd=_ap-payment&useraction=commit&token=' . urldecode( $response['TOKEN'] );
header( 'Location: ' . $paypalurl );
exit;
} else {
header( 'Location: ' . wp_sanitize_redirect( add_query_arg( array( 'action' => 'ab-paypal-error', 'ab_fid' => $form_id, 'error_msg' => str_replace( ' ', '%20', $response['L_LONGMESSAGE0'] ) ), Lib\Utils\Common::getCurrentPageURL() ) ) );
exit;
}
}
/**
* Send the NVP Request to the PayPal
*
* #param $method
* #param array $data
* #return array
*/
public function sendNvpRequest( $method, array $data )
{
$url = 'https://api-3t' . get_option( 'ab_paypal_ec_mode' ) . '.paypal.com/nvp';
$curl = new Lib\Curl\Curl();
$curl->options['CURLOPT_SSL_VERIFYPEER'] = false;
$curl->options['CURLOPT_SSL_VERIFYHOST'] = false;
$data['METHOD'] = $method;
$data['VERSION'] = '76.0';
$data['USER'] = get_option( 'ab_paypal_api_username' );
$data['PWD'] = get_option( 'ab_paypal_api_password' );
$data['SIGNATURE'] = get_option( 'ab_paypal_api_signature' );
$httpResponse = $curl->post( $url, $data );
if ( ! $httpResponse ) {
exit( $curl->error() );
}
// Extract the response details.
parse_str( $httpResponse, $PayPalResponse );
if ( ! array_key_exists( 'ACK', $PayPalResponse ) ) {
exit( 'Invalid HTTP Response for POST request to ' . $url );
}
return $PayPalResponse;
}
public static function renderForm( $form_id )
{
$html = '<form method="post" class="ab-paypal-form">';
$html .= '<input type="hidden" name="action" value="ab-paypal-checkout"/>';
$html .= '<input type="hidden" name="ab_fid" value="' . $form_id . '"/>';
$html .= '<button class="ab-left ab-back-step ab-btn ladda-button" data-style="zoom-in" data-spinner-size="40"><span class="ladda-label">' . Lib\Utils\Common::getTranslatedOption( 'ab_appearance_text_button_back' ) . '</span></button>';
$html .= '<button class="ab-right ab-next-step ab-btn ladda-button" data-style="zoom-in" data-spinner-size="40"><span class="ladda-label">' . Lib\Utils\Common::getTranslatedOption( 'ab_appearance_text_button_next' ) . '</span></button>';
$html .= '</form>';
echo $html;
}
/**
* #return array
*/
public function getProducts()
{
return $this->products;
}
/**
* Add the Product for payment
*
* #param \stdClass $product
*/
public function addProduct( \stdClass $product )
{
$this->products[] = $product;
}
}
so i'm trying about 2 3 with this and i can't managed to make it work.
I have this theme : Aruna and he has front end post and when i'm posting a image
i need to write title and upload a image from my computer ,
ok after i done this , he put the image that i upload into one custom field by theme:
The trick is when i want to upload a image from front end i wanna put it automatically on Featured image.
If i use User submited post plugin and i post from him it works .. but i wanna modifiy on my own front end.
It's important for me to make this work because i share a lot on facebook and other social media and feature image do the thing :)
I don't know what code to put here but i try to show you :
Functions.php
case "window-image":
$format = 'image';
$title = esc_html($_POST['title_image']);
$image = esc_url($_POST['postimage']);
$tags = $_POST['tags_image'];
$comments = isset($_POST['comments_image']) ? 1 : 0;
$anonymous = isset($_POST['anonymous_image']) ? 1 : 0;
$comment_status = $comments == 1 ? 'open' : 'closed';
$user_id = $id;
if(($_FILES['image_imagepost']['error'] != 0 && $image == '') || $title == '') {
wp_redirect(home_url('/') . '?posterror=1');
exit;
}
$post = array(
'comment_status' => $comment_status,
'ping_status' => 'open',
'post_author' => $user_id,
'post_content' => '',
'post_status' => $status,
'post_title' => $title,
'post_type' => 'post',
);
$post_id = wp_insert_post($post);
if($image != '') {
$pattern = '~' . get_bloginfo('url') . '~';
if(preg_match($pattern, $image) ) {
add_post_meta($post_id, '_standard_image', $image);
}
else {
//we have an external image :) we save it with the cURL library
$filedetails = pathinfo($image);
$mime = '';
if($filedetails['extension'] == 'jpe' || $filedetails['extension'] == 'jpg' || $filedetails['extension'] == 'jpeg') {
$mime = 'image/jpeg';
}
elseif($filedetails['extension'] == 'png') {
$mime = 'image/png';
}
elseif($filedetails['extension'] == 'gif') {
$mime = 'image/gif';
}
if($mime != '') {
require_once( ABSPATH . "wp-admin" . '/includes/image.php' );
$ch = curl_init($image);
$uploaddir = wp_upload_dir();
$filename = $filedetails['filename'] . rand(1, 9999) . '.' . $filedetails['extension'];
//we add some random digits to make sure it's unique
$fp = fopen(trailingslashit($uploaddir['path']) . $filename, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
$guid = trailingslashit($uploaddir['url']) . $filename;
$attachment = array(
'post_mime_type' => $mime,
'guid' => $guid,
'post_title' => '[External image] : ' . $filedetails['filename'] ,
'post_content' => '',
'post_author' => $user_id,
'post_status' => 'inherit',
'post_date' => date( 'Y-m-d H:i:s' ),
'post_date_gmt' => date( 'Y-m-d H:i:s' )
);
// Add the file to the media library and generate thumbnail.
$attach_id = wp_insert_attachment( $attachment, trailingslashit($uploaddir['url']) . $filename, $post_id );
$attach_data = wp_generate_attachment_metadata( $attach_id, trailingslashit($uploaddir['path']) . $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
add_post_meta($post_id, '_standard_image', trailingslashit($uploaddir['url']) . $filename);
}
}
}
else {
if($_FILES['image_imagepost']['error'] == 0) {
$image = $tmp->saveUpload( 'image_imagepost' );
add_post_meta($post_id, '_standard_image', wp_get_attachment_url($image['attachment_id']) );
}
}
HTML code on front end
<textarea name="title_image" class="form-control" rows="1" placeholder="<?php _e('Post title', 'Aruna');?>"></textarea>
<input type="file" name="image_imagepost" />
<input type="file" name="image_imagepost" /> this do the trick for upload on custom field ...
I can't understand , when i'm posting videos(yt) he take the thumbnail automatically and put it on featured image, I try to take a look at video and image and unsuccessful:
Here is the video code :
<?php
case "window-video":
$format = 'video';
$title = esc_html($_POST['title_video']);
$tags = $_POST['tags_video'];
if($title == '') {
wp_redirect(home_url('/') . '?posterror=1');
exit;
}
$comments = isset($_POST['comments_video']) ? 1 : 0;
$anonymous = isset($_POST['anonymous_video']) ? 1 : 0;
$comment_status = $comments == 1 ? 'open' : 'closed';
$user_id = $id;
$post = array(
'comment_status' => $comment_status,
'ping_status' => 'open',
'post_author' => $user_id,
'post_content' => '',
'post_status' => $status,
'post_title' => $title,
'post_type' => 'post',
);
$post_id = wp_insert_post($post);
if(isset($_FILES['video_file']) && $_FILES['video_file']['error'] == 0) {
$video_file = $tmp->saveUpload( 'video_file' );
add_post_meta($post_id, '_video_localvideo', wp_get_attachment_url($video_file['attachment_id']) );
}
else {
$video = esc_url($_POST['video']);
if (strpos($video,'youtube') !== false) {
//it's youtube, we need toget the thumbnail! :)
//we get the id of the video first
$videotemp = explode('/watch?v=', $video);
if(isset($videotemp[1]) && $videotemp[1] != '') {
$idvideo = $videotemp[1];
//we have the id, now we put the thumbnail
$url_video = 'http://i1.ytimg.com/vi/' . $idvideo . '/hqdefault.jpg';
}
}
elseif (strpos($video,'vimeo') !== false) {
//it's youtube, we need toget the thumbnail! :)
//we get the id of the video first
$videotemp = explode('vimeo.com/', $video);
if(isset($videotemp[1]) && $videotemp[1] != '') {
$idvideo = $videotemp[1];
//we have the id, now we put the thumbnail
$json_vimeo = 'http://vimeo.com/api/v2/video/' . $idvideo . '.json';
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $json_vimeo);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$json_vimeo = curl_exec($ch);
curl_close($ch);
$jsontemp = json_decode($json_vimeo, true);
if(isset($jsontemp[0]) && isset($jsontemp[0]['thumbnail_large']) && $jsontemp[0]['thumbnail_large'] != '') {
$url_video = $jsontemp[0]['thumbnail_large'];
}
}
}
if(isset($url_video) && $url_video != '') {
//we have an external youtube image :) we save it with the cURL library
$filedetails = pathinfo($url_video);
$mime = '';
if($filedetails['extension'] == 'jpe' || $filedetails['extension'] == 'jpg' || $filedetails['extension'] == 'jpeg') {
$mime = 'image/jpeg';
}
elseif($filedetails['extension'] == 'png') {
$mime = 'image/png';
}
elseif($filedetails['extension'] == 'gif') {
$mime = 'image/gif';
}
if($mime != '') {
require_once( ABSPATH . "wp-admin" . '/includes/image.php' );
$ch = curl_init($url_video);
$uploaddir = wp_upload_dir();
$filename = $filedetails['filename'] . rand(1, 9999) . '.' . $filedetails['extension'];
//we add some random digits to make sure it's unique
$fp = fopen(trailingslashit($uploaddir['path']) . $filename, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
$guid = trailingslashit($uploaddir['url']) . $filename;
$attachment = array(
'post_mime_type' => $mime,
'guid' => $guid,
'post_title' => '[External image] : ' . $filedetails['filename'] ,
'post_content' => '',
'post_author' => $user_id,
'post_status' => 'inherit',
'post_date' => date( 'Y-m-d H:i:s' ),
'post_date_gmt' => date( 'Y-m-d H:i:s' )
);
// Add the file to the media library and generate thumbnail.
$attach_id = wp_insert_attachment( $attachment, trailingslashit($uploaddir['url']) . $filename, $post_id );
$attach_data = wp_generate_attachment_metadata( $attach_id, trailingslashit($uploaddir['path']) . $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
update_post_meta($post_id, '_thumbnail_id', $attach_id);
}
}
add_post_meta($post_id, '_video_externalvideo', $video);
}
$nsfw = isset($_POST['nsfw_video']) ? 1 : 2;
add_post_meta($post_id, '_video_nsfw', $nsfw);
add_post_meta($post_id, '_anonymous', $anonymous);
?>
and here is the image code :
case "window-image":
$format = 'image';
$title = esc_html($_POST['title_image']);
$image = esc_url($_POST['postimage']);
$tags = $_POST['tags_image'];
$comments = isset($_POST['comments_image']) ? 1 : 0;
$anonymous = isset($_POST['anonymous_image']) ? 1 : 0;
$comment_status = $comments == 1 ? 'open' : 'closed';
$user_id = $id;
if(($_FILES['image_imagepost']['error'] != 0 && $image == '') || $title == '') {
wp_redirect(home_url('/') . '?posterror=1');
exit;
}
$post = array(
'comment_status' => $comment_status,
'ping_status' => 'open',
'post_author' => $user_id,
'post_content' => '',
'post_status' => $status,
'post_title' => $title,
'post_type' => 'post',
);
$post_id = wp_insert_post($post);
if($image != '') {
$pattern = '~' . get_bloginfo('url') . '~';
if(preg_match($pattern, $image) ) {
add_post_meta($post_id, '_standard_image', $image);
}
else {
//we have an external image :) we save it with the cURL library
$filedetails = pathinfo($image);
$mime = '';
if($filedetails['extension'] == 'jpe' || $filedetails['extension'] == 'jpg' || $filedetails['extension'] == 'jpeg') {
$mime = 'image/jpeg';
}
elseif($filedetails['extension'] == 'png') {
$mime = 'image/png';
}
elseif($filedetails['extension'] == 'gif') {
$mime = 'image/gif';
}
if($mime != '') {
require_once( ABSPATH . "wp-admin" . '/includes/image.php' );
$ch = curl_init($image);
$uploaddir = wp_upload_dir();
$filename = $filedetails['filename'] . rand(1, 9999) . '.' . $filedetails['extension'];
//we add some random digits to make sure it's unique
$fp = fopen(trailingslashit($uploaddir['path']) . $filename, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
$guid = trailingslashit($uploaddir['url']) . $filename;
$attachment = array(
'post_mime_type' => $mime,
'guid' => $guid,
'post_title' => '[External image] : ' . $filedetails['filename'] ,
'post_content' => '',
'post_author' => $user_id,
'post_status' => 'inherit',
'post_date' => date( 'Y-m-d H:i:s' ),
'post_date_gmt' => date( 'Y-m-d H:i:s' )
);
// Add the file to the media library and generate thumbnail.
$attach_id = wp_insert_attachment( $attachment, trailingslashit($uploaddir['url']) . $filename, $post_id );
$attach_data = wp_generate_attachment_metadata( $attach_id, trailingslashit($uploaddir['path']) . $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
add_post_meta($post_id, '_standard_image', trailingslashit($uploaddir['url']) . $filename);
}
}
}
else {
if($_FILES['image_imagepost']['error'] == 0) {
$image = $tmp->saveUpload( 'image_imagepost' );
add_post_meta($post_id, '_standard_image', wp_get_attachment_url($image['attachment_id']) );
}
}
$nsfw = isset($_POST['nsfw_image']) ? 1 : 2;
add_post_meta($post_id, '_standard_nsfw', $nsfw);
add_post_meta($post_id, '_anonymous', $anonymous);
break;