I have a function like bellow
if(!function_exists('generate_share_urls')) {
function generate_share_urls() {
$title = the_title();
$content = the_content();
$share_urls = array (
'facebook' => 'http://www.facebook.com/sharer/sharer.php?u=',
'twitter' => 'http://twitter.com/share?url=',
'google_plus' => 'https://plus.google.com/share?url=',
'linkedin' => 'http://www.linkedin.com/shareArticle?mini=true&url=',
'pinterest' => 'http://pinterest.com/pin/create/button/?url=',
'email' => 'mailto:?subject={'.$title.'}&body='.$content.',
'permalink' => ''
);
return $share_urls;
}
}
Now when run the function i cant find the $title and the $content of the page. Is there any fault with my code.
the_title() and the_content() will print the title/content, not return it. What you need instead are the get_ functions:
if(!function_exists('generate_share_urls')) {
function generate_share_urls() {
$title = get_the_title();
$content = get_the_content();
$share_urls = array (
'facebook' => 'http://www.facebook.com/sharer/sharer.php?u=',
'twitter' => 'http://twitter.com/share?url=',
'google_plus' => 'https://plus.google.com/share?url=',
'linkedin' => 'http://www.linkedin.com/shareArticle?mini=true&url=',
'pinterest' => 'http://pinterest.com/pin/create/button/?url=',
'email' => 'mailto:?subject={'.$title.'}&body='.$content.',
'permalink' => ''
);
return $share_urls;
}
}
Related
I am researching more and use the code..
I have done this code.
if (!defined('ABSPATH')) {
die;
}
if(!class_exists('ArtistPublic')):
class ArtistPublic
{
public static function createTemplate( ) {
global $user_ID;
$new_post = array(
'post_title' => 'Artist',
'post_content' => 'hello Artist',
'post_status' => 'publish',
'post_date' => date('Y-m-d H:i:s'),
'post_author' => $user_ID,
'post_type' => 'page',
);
$post_id = wp_insert_post($new_post);
if( !$post_id )
wp_die('Error creating template page');
else
update_post_meta( $post_id, '_wp_page_template', 'artist.php' );
// Filter page template
// add_filter('page_template', 'catch_plugin_template');
}
// Page template filter callback
public static function catch_plugin_template($template) {
if( is_page_template('artist.php') )
$template = WP_PLUGIN_DIR . '/ItgArtist/public/templates/artist.php';
return $template;
}
}
endif;
but create multiple page after refresh.
Is there any good way to create the page like as woocommerce does??
So code be like something
if (!defined('ABSPATH')) {
die;
}
if(!class_exists('ArtistPublic')):
class ArtistPublic {
public static function createTemplate( ) {
if( get_option('artist_page_id') ) :
global $user_ID;
$new_post = array(
'post_title' => 'Artist',
'post_content' => 'hello Artist',
'post_status' => 'publish',
'post_date' => date('Y-m-d H:i:s'),
'post_author' => $user_ID,
'post_type' => 'page',
);
$post_id = wp_insert_post($new_post);
if( !$post_id ) :
wp_die('Error creating template page');
else :
update_option('artist_page_id', $post_id);
update_post_meta( $post_id, '_wp_page_template', 'artist.php' );
endif;
endif;
// Filter page template
// add_filter('page_template', 'catch_plugin_template');
}
// Page template filter callback
public static function catch_plugin_template($template) {
if( is_page_template('artist.php') )
$template = WP_PLUGIN_DIR . '/ItgArtist/public/templates/artist.php';
return $template;
}
}
endif;
I am trying to update my repeater field from front end-with files. In case with one field file - it works. But when I'm trying to fill repeater with files it doesn't work.
// JS. Ajaxly sending files
var ajaxurl = '<?php echo site_url() ?>/wp-admin/admin-ajax.php';
$('.js-new-msg-send').click(function (e) {
e.preventDefault();
var form = document.forms.namedItem("new_theme");
var formData = new FormData(form);
formData.append('user_id', '<?php echo $userID; ?>');
formData.append('action', 'msg_to_acf');
var xhr = new XMLHttpRequest();
xhr.open('POST', ajaxurl, true);
xhr.send(formData);
})
I found function to handle files uploading to acf field and modified it to handle multiple files from $_FILES variable:
// FOR MULTIPLE FILES
if ( !empty($_FILES[$f]['name']) && is_array($_FILES[$f]['name']) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$file_list = array();
foreach ($_FILES[$f]['name'] as $key => $value) {
$temp_file = array(
'name' => $_FILES[$f]['name'][$key],
'type' => $_FILES[$f]['type'][$key],
'tmp_name' => $_FILES[$f]['tmp_name'][$key],
'error' => $_FILES[$f]['error'][$key],
'size' => $_FILES[$f]['size'][$key]
);
wp_update_attachment_metadata( $pid, $temp_file );
$file = wp_handle_upload( $temp_file , array('test_form' => FALSE, 'action' => 'editpost') );
if ( isset( $file['error'] )) {
return new WP_Error( 'upload_error', $file['error'] );
}
$file_type = wp_check_filetype($temp_file['name'], array(
'jpg|jpeg' => 'image/jpeg',
'gif' => 'image/gif',
'png' => 'image/png',
));
if ($file_type['type']) {
$name_parts = pathinfo( $file['file'] );
$name = $file['filename'];
$type = $file['type'];
$title = $t ? $t : $name;
$content = $c;
$attachment = array(
'post_title' => $title,
'post_type' => 'attachment',
'post_content' => $content,
'post_parent' => $pid,
'post_mime_type' => $type,
'guid' => $file['url'],
);
foreach( get_intermediate_image_sizes() as $s ) {
$sizes[$s] = array( 'width' => '', 'height' => '', 'crop' => true );
$sizes[$s]['width'] = get_option( "{$s}_size_w" ); // For default sizes set in options
$sizes[$s]['height'] = get_option( "{$s}_size_h" ); // For default sizes set in options
$sizes[$s]['crop'] = get_option( "{$s}_crop" ); // For default sizes set in options
}
$sizes = apply_filters( 'intermediate_image_sizes_advanced', $sizes );
foreach( $sizes as $size => $size_data ) {
$resized = image_make_intermediate_size( $file['file'], $size_data['width'], $size_data['height'], $size_data['crop'] );
if ( $resized )
$metadata['sizes'][$size] = $resized;
}
$attach_id = wp_insert_attachment( $attachment, $file['file'] /*, $pid - for post_thumbnails*/);
if ( !is_wp_error( $id )) {
$attach_meta = wp_generate_attachment_metadata( $attach_id, $file['file'] );
wp_update_attachment_metadata( $attach_id, $attach_meta );
}
$final_temp_arr = array(
'pid' =>$pid,
'url' =>$file['url'],
'file'=>$file,
'attach_id'=>$attach_id
);
array_push($file_list, $final_temp_arr);
}
}
return $file_list;
}
In final, I using this function to get an array of information with attach-id variable that I inserting to repeater.
$att = my_update_attachment( 'msg-file-list' , $post_id );
$files_final_list = array();
foreach ($att as $key => $val) {
array_push($files_final_list, $val['attach_id']);
}
$value_arr = array(
array(
"msg-author" => $user_name,
"msg-date" => $date,
"msg-read-check" => true,
"msg-cont" => $msg_cont,
'msg-file-list' => $files_final_list
)
);
update_field( 'test_file_list' , $files_final_list , $post_id );
I guess that mistake is in last part , where I trying to upload files to repeater. Can someone show me what I'am doing wrong? Thanks for helping.
Here's my code:
I'd like to only return posts of logged in user.
I am populating a dropdown form in WordPress gravity forms.
$current_user = _wp_get_current_user();
function populate_posts( $form) {
foreach ( $form['fields'] as &$field ) {
if ( $field->type != 'select' || strpos( $field->cssClass, 'populate-posts' ) === false ) {
continue;
}
$posts = get_posts( 'post_type=credit cards&numberposts=-1&post_status=publish&author=$current_user' );
$choices = array();
foreach ( $posts as $post ) {
$choices[] = array( 'text' => $post->post_title, 'value' => $post->post_title );
}
$field->placeholder = 'Select Credit Card';
$field->choices = $choices;
}
As i understand question of your's is to get "Post of Current User".Then here is a below code of it.
1) You need to pass author ID(Current User ID) as argument.
$current_user = wp_get_current_user();
$args = array(
'author' => $current_user->ID,
'orderby' => 'post_date',
'order' => 'ASC',
);
2) Pass above argument is post as below :
$current_user_posts = get_posts( $args );
I Hope this helps you.
You can also use WP_Query()
$user = wp_get_current_user();
$query_args = array(
'post_type' => 'post',
'author' => $user->ID,
);
$query = new WP_Query($query_args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$post = $query->post;
echo $post->post_title;
}
wp_reset_postdata();
}
else{
echo 'No posts found.';
}
I am challenging Ajax implementation when replying by "BBPress".
However, reply posted in this manner is displayed in the dashboard, but it is not displayed in the loop of the replies list.
This will be displayed in the loop of the replies list only when you click "Update" on the dashboard.
I want to know the code that displays correctly in the loop.
This is my code:
my-reply.js
"use strict";
(function($){
$(document).on("click","#bbp_reply_submit", function() {
// get
var inputForum = '56'; //There is only one forum.
var inputTopic = $('#bbp_topic_id').val();
var inputTitle = $('#bbp-reply-form-info').text();
var inputContent = $('#bbp_reply_input').val();
var inputParent = $('#bbp_reply_to').val();
var inputIp = $('#my_reply_ip').val();
// Ajax
$.ajax({
url: MY_AJAX.api,
type: 'POST',
data: {
// action name
action: MY_AJAX.action,
// nonce
nonce: MY_AJAX.nonce,
// submit data
submitForum: inputForum,
submitTopic: inputTopic,
submitTitle: inputTitle,
submitContent: inputContent,
submitParent: inputParent,
submitIp: inputIp,
}
})
// scusess
.done(function( response ) {
alert('success'); // Actually, I will display reply instead of alerts.
})
// error
.fail(function( jqXHR, textStatus, errorThrown ) {
alert('error');
});
});
})(jQuery);
functions.php
// nonce
function my_enqueue_scripts() {
$handle = 'my-script';
$jsFile = 'path/to/myscript.js';
wp_register_script($handle, $jsFile, ['jquery']);
$acrion = 'my-ajax-action';
wp_localize_script($handle, 'MY_AJAX', [
'api' => admin_url( 'admin-ajax.php' ),
'action' => $acrion,
'nonce' => wp_create_nonce( $acrion ),
]);
wp_enqueue_script($handle);
}
add_action( 'wp_enqueue_scripts', 'my_enqueue_scripts' );
// post reply
function my_ajax_event() {
$action = 'my-ajax-action';
if( check_ajax_referer($action, 'nonce', false) ) {
$submitForum = esc_html( $_POST['submitForum'] );
$submitTopic = esc_html( $_POST['submitTopic'] );
$submitTitle = esc_html( $_POST['submitTitle'] );
$submitContent = esc_html( $_POST['submitContent'] );
$submitParent = esc_html( $_POST['submitParent'] );
$submitIp = esc_html( $_POST['submitIp'] );
$submitTopicslug = esc_html( $_POST['submitTopicslug'] );
$page = get_post( $submitTopic );
$slug = $page->post_name;
$date = 'Y-m-d H:i:s';
$my_post = array(
'post_title' => (string)wp_strip_all_tags($_POST['submitTitle']),
'post_content' => (string)$_POST['submitContent'],
'post_status' => 'publish',
'post_author' => get_current_user_id(),
'post_type' => 'reply',
'meta_input' => array(
'_bbp_forum_id' => $_POST['submitForum'],
'_bbp_topic_id' => $_POST['submitTopic'],
'_bbp_reply_to' => $_POST['submitParent'],
'_bbp_author_ip' => $_POST['submitIp'],
'_edit_last' => get_current_user_id(),
'_bbp_topic_sort_desc' => 'dft',
'_bbp_sort_desc' => 'dft',
'_bbp_topic_sort_show_lead_topic' => 'dft',
'_bbp_topic_sort_show_lead_topic_forum' => 'dft',
'_wp_old_slug' => $slug,
'_bbp_last_active_time' => $date,
'_bbp_reply_count' => '',
'_bbp_engagement' => '',
'_bbp_reply_count_hidden' => '',
'_bbp_voice_count' => '',
)
);
wp_insert_post( $my_post );
} else {
status_header( '403' );
}
die();
}
add_action( 'wp_ajax_my-ajax-action', 'my_ajax_event' );
add_action( 'wp_ajax_nopriv_my-ajax-action', 'my_ajax_event' );
I am trying to make a Custom Gateway Plugin for my Merchant Account but I got stuck and I don't know how to continue.
Now, here is what I done so far:
<?php
/*
Plugin Name: Paysecure.ro Payment Gateway
Plugin URI: http://www.Paysecure.ro
Description: Allows you to use Paysecure.ro Payment Gateway with the WooCommerce plugin.
Version: 0.0.1
Author: Andrei Raileanu
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
add_action('plugins_loaded', 'woocommerce_Paysecure', 0);
function woocommerce_Paysecure(){
if (!class_exists('WC_Payment_Gateway'))
return; // if the WC payment gateway class is not available, do nothing
if(class_exists('WC_Paysecure'))
return;
class WC_Gateway_Paysecure extends WC_Payment_Gateway{
public function __construct(){
$plugin_dir = plugin_dir_url(__FILE__);
global $woocommerce;
$this->id = 'Paysecure';
$this->icon = apply_filters('woocommerce_Paysecure_icon', ''.$plugin_dir.'Paysecure.png');
$this->has_fields = true;
// Load the settings
$this->init_form_fields();
$this->init_settings();
// Define user set variables
$this->title = "Credit/Debit Card";
$this->description = "You will be redirected to paysecure.ro to complete your purchase.";
$this->cui = "XXXXXXXXX";
$this->encryption_key = "XXXXXXXXX";
$this->currency = "USD";
// Logs
if ($this->debug == 'yes'){
$this->log = $woocommerce->logger();
}
// Actions
add_action('woocommerce_receipt_' . $this->id, array($this, 'receipt_page'));
// Save options
add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
// Payment listener/API hook
add_action('woocommerce_api_wc_' . $this->id, array($this, 'check_ipn_response'));
}
function init_form_fields()
{
$this->form_fields = array(
'enabled' => array(
'title' => __( 'Enable/Disable', 'woocommerce' ),
'type' => 'checkbox',
'label' => __( 'Enable Paysecure', 'woocommerce' ),
'default' => 'yes'
)
);
}
public function admin_options() {
?>
<h3><?php _e( 'Paysecure', 'woocommerce' ); ?></h3>
<p><?php _e( 'Paysecure Payment Gateway', 'woocommerce' ); ?></p>
<table class="form-table">
<?php $this->generate_settings_html(); ?>
</table>
<?php
}
function payment_fields() {
$plugin_dir = plugin_dir_url(__FILE__);
// Description of payment method from settings
if ($this->description) { ?>
<p><?php
echo $this->description; ?>
</p><?php
} ?>
<?php
}
function process_payment( $order_id ) {
global $woocommerce;
$order = new WC_Order($order_id);
// I WILL NEED THESE FIELDS
//$this->notify_url;
//$order->get_total();
//$order->get_order_number();
//$order->billing_first_name;
//$order->billing_email;
}
}
function add_Paysecure_gateway($methods){
$methods[] = 'WC_Gateway_Paysecure';
return $methods;
}
add_filter('woocommerce_payment_gateways', 'add_Paysecure_gateway');
}
Here are the PHP instructions from my merchant account provider:
<?php
require_once('./functions.php');
$key = 'THIS IS THE ENCRYPTION KEY';
$data = array( 'cui' => 'THIS IS THE CUI CODE',
'AMOUNT' => '200',
'CURRENCY' => 'USD',
'ORDER' => '12313',
'DESC' => ps_clean('SHORT DESCRIPTION'),
'PENTRU' => 'EMAIL ADDRESS',
'TRTYPE' => 0,
'BACKREF' => 'http://www.site.ro/test.php',
'TIMESTAMP'=>time()
);
echo '<form action="https://paysecure.ro/order/cgi-bin/" method="post" >';
foreach ($data as $l => $v ) echo '<input size="55" readonly type="text" name="'.$l.'" value="'.$v.'" /> : <label for="'.$l.'">'.$l.'</label><br>';
echo '<input size="55" type="text" name="P_SIGN" readonly value="'.calculateSign($data,$key).'" /><br>' ; //se calculeaza P_SIGN - ul , encriptarea datelor
?>
<input type="submit" />
</form>
Can someone help me with the rest of the code?
1st mistake I noticed you made, $this->id MUST be in lowercase. 'Paysecure' is not gonna work here come time for the API hook.
// Payment listener/API hook
add_action('woocommerce_api_wc_' . $this->id, array($this, 'check_ipn_response'));
change to this instead:
// Payment listener/API hook
add_action('woocommerce_api_wc_paysecure', array($this, 'check_ipn_response'));
2nd mistake is that you forgot to create the function check_ipn_response()
// Handles the callbacks received from the payment backend. give this url to your payment processing comapny as the ipn response URL:
// USAGE: http://myurl.com/?wc-api=WC_Gateway_Paysecure
function check_ipn_response() {
$http_contents = file_get_contents("php://input");
$json = json_decode($http_contents, true);
$order = new WC_Order($json['custom']);
if ($callback_json['status'] == 'Transaction approved')
{
$order->payment_complete(); //This will ensure stock reductions are made, and the status is changed to the correct value.
$order->add_order_note( __( 'KiwiPay Transaction Approved.', 'kiwipay' ) );
}
else
{
$order->update_status('failed');
$order->add_order_note('KiwiPay status received - ' . $callback_json['status']);
}
//references:
//http://docs.woothemes.com/document/payment-gateway-api/
//https://github.com/Paymium/WooCommerce/blob/master/checkout.php
//https://github.com/tubiz/voguepay-woocommerce-payment-gateway/blob/master/voguepay-woocommerce-payment-gateway.php
/*
{
"id":1863,
"amount":1750,
"status":"Transaction approved",
"created":1434198776,
"reference":"2626", //this is the order number $order->get_order_number()
"name":"HamishTest Test",
"email":"hamish#tst.xom",
"address":{"street":"my rd","region":"N/A","city":"tauranga","zip":"3175","country":"NZ"},
"test":true,
"price":"17.50",
"custom":"6589" //this is the wc order_id passed during process_payment to the paymen processor.
}
*/
How about this?
add_action( 'plugins_loaded', 'init_gateway_cash' );
function init_gateway_cash() {
class WC_Gateway_Cash extends WC_Payment_Gateway {
function __construct() {
$this->id = "Cash Gateway";
$this->title = "Cash";
$this->description = "More later";
$this->init_form_fields();
$this->init_settings();
add_action( 'woocommerce_update_options_payment_gateways', array( &$this, 'process_admin_options' ) );
}
function init_form_fields(){
$this->form_fields = array(
'enabled' => array(
'title' => __( 'Enable/Disable', 'woocommerce' ),
'type' => 'checkbox',
'label' => __( 'Enable Cheque Payment', 'woocommerce' ),
'default' => 'yes'
),
'title' => array(
'title' => __( 'Title', 'woocommerce' ),
'type' => 'text',
'description' => __( 'This controls the title which the user sees during checkout.', 'woocommerce' ),
'default' => __( 'Cheque Payment', 'woocommerce' ),
'desc_tip' => true,
),
'description' => array(
'title' => __( 'Customer Message', 'woocommerce' ),
'type' => 'textarea',
'default' => ''
)
);
}
function process_payment( $order_id ) {
global $woocommerce;
$order = new WC_Order( $order_id );
$productArray = array();
$x = 0;
foreach( $order->get_items() as $item_id => $item ) {
$productArray[$x] = $order->get_product_from_item( $item );
$x++;
}
// Mark as on-hold (we're awaiting the cheque)
$order->update_status('on-hold',
__( 'Awaiting cheque payment.', 'woocommerce' )
);
// Remove cart
$woocommerce->cart->empty_cart();
// Return thankyou redirect
return array(
'result' => 'success',
'redirect' => $this->get_return_url( $order )
);
}
}
}
function add_gateway_cash_class ($methods ) {
$methods[] = 'WC_Gateway_Cash';
return $methods;
}
add_filter( 'woocommerce_payment_gateways', 'add_gateway_cash_class' );