Custom FacetWP will not show in front-end of WordPress - php

I am not sure why my custom FacetWP facet will not render on the front end of WordPress
I need a custom FacetWP dropdown that shows the user options such as: today, tomorrow, December by taking in two acf fields of
event_date_start and event_date_end and filtering the posts based on this range.
I have attempted to set up the facet as follows:
First, create a custom facet type in FacetWP by adding this code to functions.php file:
add_filter( 'facetwp_facet_types', function( $types ) {
$types['custom_dropdown'] = array(
'label' => 'Custom Dropdown',
'query_type' => 'custom',
);
return $types;
});
Next, the custom query code in functions.php file:
add_filter( 'facetwp_query_args', function( $query_args, $renderer ) {
$params = $renderer->$params;
if ( 'custom_dropdown' == $params['facet']['type'] ) {
$selected = $params['selected_values'][0];
switch ( $selected ) {
case 'today':
$selected_date = strtotime( 'today' );
break;
case 'tomorrow':
$selected_date = strtotime( 'tomorrow' );
break;
case 'December':
$selected_date = strtotime( 'December' );
break;
}
$query_args['meta_query'][] = array(
'relation' => 'AND',
array(
'key' => 'event_date_start',
'value' => $selected_date,
'compare' => '<=',
'type' => 'NUMERIC',
),
array(
'key' => 'event_date_end',
'value' => $selected_date,
'compare' => '>=',
'type' => 'NUMERIC',
),
);
}
return $query_args;
}, 10, 2 );
Add the custom dropdown options to the facet settings in functions.php file:
add_filter( 'facetwp_render_output', function( $output, $params ) {
if ( 'custom_dropdown' == $params['facet']['type'] ) {
$output = '<select>';
$options = array( 'today', 'tomorrow', 'December' );
foreach ( $options as $option ) {
$selected = ( $option == $params['selected_values'][0] ) ? ' selected' : '';
$output .= '<option value="' . $option . '"' . $selected . '>' . $option . '</option>';
}
$output .= '</select>';
}
return $output;
}, 10, 2 );
I have placed this shortcode on the front end:
[facetwp facet="custom_dropdown"]
I have also tried to set the Date Source to be 'custom' but this does not work either:
add_filter( 'facetwp_facet_sources', function( $sources ) {
$sources['custom'] = array(
'label' => 'Custom Values',
'choices' => array(
'today' => 'Today',
'tomorrow' => 'Tomorrow',
'December' => 'December'
),
'props' => array(
'data_type' => 'custom'
)
);
return $sources;
});
If someone knows what the issue could be I would really appreciate if someone can help.

Related

Implementing Rawg Api wordpress not working

I try to implement the Rawg.io API to my Wordpress Functions.php File but it doesn't work, i tried my code with another API and it is working fine, i think it has something to do with the API link Page='.$current_page.'
as you can see i created an custom post type to add the games to.
i also created custom fields with the right field keys.
My Report.txt file keeps returning current page = 1
function register_game_cpt() {
register_post_type( 'game', array(
'label' => 'Games',
'public' => true,
'capability_type' => 'post',
'supports' => array('title', 'editor', 'thumbnail'),
'taxonomies' => array('recordings', 'category', 'whatever', 'post_tag'),
));
}
add_action( 'init', 'register_game_cpt' );
// if ( ! wp_next_scheduled( 'update_game_list' ) ) {
// wp_schedule_event( time(), 'weekly', 'update_game_list' );
// }
add_action( 'update_game_list', 'get_games_from_api' );
add_action( 'wp_ajax_nopriv_get_games_from_api', 'get_games_from_api' );
add_action( 'wp_ajax_get_games_from_api', 'get_games_from_api' );
function get_games_from_api() {
$file = get_stylesheet_directory() . '/report.txt';
$current_page = ( ! empty( $_POST['current_page'] ) ) ? $_POST['current_page'] : 1;
$games = [];
// Should return an array of objects
$results = wp_remote_retrieve_body(wp_remote_get('https://api.rawg.io/api/games?key=/////////////////////&page='.$current_page.'&page_size=40'));
file_put_contents($file, "Current Page: " . $current_page. "\n\n", FILE_APPEND);
// turn it into a PHP array from JSON string
$results = json_decode( $results );
// Either the API is down or something else spooky happened. Just be done.
if( ! is_array( $results ) || empty( $results ) ){
return false;
}
$games[] = $results;
foreach( $games[0] as $game ){
$game_slug = sanitize_title( $game->name . '-' . $game->id );
$existing_game = get_page_by_path( $game_slug, 'OBJECT', 'game' );
if( $existing_game === null ){
$inserted_game = wp_insert_post( [
'post_name' => $game_slug,
'post_title' => $game_slug,
'post_type' => 'game',
'post_status' => 'publish'
] );
if( is_wp_error( $inserted_game ) || $inserted_game === 0 ) {
die('Could not insert game: ' . $game_slug);
error_log( 'Could not insert game: ' . $game_slug );
continue;
}
// add meta fields
$fillable = [
'field_62684fc72d524' => 'count',
'field_6266cb41982d3' => 'name',
'field_6266cb4c982d4' => 'publishers',
'field_6266cb54982d5' => 'genres',
'field_6266cb64012e9' => 'platforms',
'field_6266cb722ebe8' => 'dates',
'field_626850012d525' => 'results',
];
foreach( $fillable as $key => $name ) {
update_field( $key, $game->$name, $inserted_game );
}
} else {
$existing_game_id = $existing_game->ID;
$exisiting_game_timestamp = get_field('updated_at', $existing_game_id);
if( $game->updated_at >= $exisiting_game_timestamp ){
$fillable = [
'field_62684fc72d524' => 'count',
'field_6266cb41982d3' => 'name',
'field_6266cb4c982d4' => 'publishers',
'field_6266cb54982d5' => 'genres',
'field_6266cb64012e9' => 'platforms',
'field_6266cb722ebe8' => 'dates',
'field_626850012d525' => 'results',
];
foreach( $fillable as $key => $name ){
update_field( $name, $game->$name, $existing_game_id);
}
}
}
}
$current_page = $current_page + 1;
wp_remote_post( admin_url('admin-ajax.php?action=get_games_from_api'), [
'blocking' => false,
'sslverify' => false, // we are sending this to ourselves, so trust it.
'body' => [
'current_page' => $current_page
]
] );
}

Generate woocommerce coupon after gravity form submission

I want a user to enter their email in a gravity form and after submission they are emailed a unique coupon code that expires after two weeks. I have cobble together code from a few other solutions and I am successful at creating the unique code. But I can't get it to create the coupon in woocommerce.. Not being a PHP master I know I'm missing something obvious.
//* Define options/constants
define( 'ENGWP_FORM_ID', 276 ); // The ID of the form (integer)
define( 'ENGWP_SOURCE_FIELD_ID', 2 ); // The ID of the form field holding the code (integer)
define( 'ENGWP_CODE_LENGTH', 12 ); // Length of code (integer)
define( 'ENGWP_CODE_CHARS', '1234567890QWERTYUIOPASDFGHJKLZXCVBNM' ); // Available character for the code; default 0-9 and uppercase letters (string)
define( 'ENGWP_CODE_PREFIX', '17-' ); // Custom prefix for the code (string); default empty
define( 'ENGWP_DISCOUNT_TYPE', 'percent' ); // 'flat' or 'percent' (string)
define( 'ENGWP_DISCOUNT_AMOUNT', 10 ); // Value of discount (integer); $ if 'type' is 'flat' and % if 'type' is 'percent'
define( 'ENGWP_MAX_USES', 1 ); // Maximum number of uses per customer (integer)
define( 'ENGWP_MIN_PRICE', 0 ); // Minimum price for discount to apply (integer); default none
define( 'ENGWP_PRODUCT_REQS', '' ); // A comma-separated list of product IDs (string) the coupons apply to
define( 'ENGWP_REQS_CONDITION', '' ); // How to apply the discount to those products (string); accepts 'any' (at least one product ID must be in the cart) or 'all' (all products must be in the cart)
define( 'ENGWP_SINGLE_USE', 'use_once' ); // Whether the coupons generated can be used more than once by a single customer; default is set to one-time usage but can be set to false (boolean) for allowing multiple uses
define( 'ENGWP_EXCLUDE_PRODUCTS', '' ); // A comma-separated list of product IDs (string) to exclude from discount-applicability
$start_date = ''; # no date
// $start_date = '01/01/1900'; # static date
// $start_date = date( 'm/d/Y', strtotime("yesterday") );
$exp_date = date( 'm/d/Y', strtotime("+14 days") );
// $exp_date = '01/01/1900'; # static date
// $exp_date = ''; # no date
class GW_Create_Coupon {
public function __construct( $args = array() ) {
// set our default arguments, parse against the provided arguments, and store for use throughout the class
$this->_args = wp_parse_args( $args, array(
'form_id' => false,
'source_field_id' => false,
'plugin' => 'wc',
'amount' => 0,
'type' => '',
'meta' => array()
) );
// do version check in the init to make sure if GF is going to be loaded, it is already loaded
add_action( 'init', array( $this, 'init' ) );
}
public function init() {
// make sure we're running the required minimum version of Gravity Forms
if( ! property_exists( 'GFCommon', 'version' ) || ! version_compare( GFCommon::$version, '1.8', '>=' ) ) {
return;
}
add_action( 'gform_after_submission', array( $this, 'create_coupon' ), 10, 2 );
}
public function create_coupon( $entry, $form ) {
if( ! $this->is_applicable_form( $form ) ) {
return;
}
$coupon_code = rgar( $entry, $this->_args['source_field_id'] );
$amount = $this->_args['amount'];
$type = $this->_args['type'];
$plugin_func = array( $this, sprintf( 'create_coupon_%s', $this->_args['plugin'] ) );
if( is_callable( $plugin_func ) ) {
call_user_func( $plugin_func, $coupon_code, $amount, $type );
}
}
public function create_coupon_wc( $coupon_code, $amount, $type ) {
$coupon = array(
‘post_title’ => $coupon_code,
‘post_content’ => ”,
‘post_status’ => ‘publish’,
‘post_author’ => 1,
‘post_type’ => ‘shop_coupon’
);
$new_coupon_id = wp_insert_post( $coupon );
$meta = wp_parse_args( $this->_args[‘meta’], array(
‘discount_type’ => $type,
‘coupon_amount’ => $amount,
‘individual_use’ => ‘yes’,
‘product_ids’ => ”,
‘exclude_product_ids’ => ”,
‘usage_limit’ => ‘1’,
‘expiry_date’ => ”,
‘apply_before_tax’ => ‘no’,
‘free_shipping’ => ‘no’,
‘exclude_sale_items’ => ‘no’,
‘product_categories’ => ”,
‘exclude_product_categories’ => ”,
‘minimum_amount’ => ”,
‘customer_email’ => ”
) );
foreach( $meta as $meta_key => $meta_value ) {
update_post_meta( $new_coupon_id, $meta_key, $meta_value );
}
}
public function create_coupon_edd( $coupon_code, $amount, $type ) {
if( ! is_callable( 'edd_store_discount' ) ) {
return;
}
$meta = wp_parse_args( $this->_args['meta'], array(
'name' => $coupon_code,
'code' => $coupon_code,
'type' => $type,
'amount' => $amount,
'excluded_products' => array(),
'expiration' => '',
'is_not_global' => false,
'is_single_use' => false,
'max_uses' => '',
'min_price' => '',
'product_condition' => '',
'product_reqs' => array(),
'start' => '',
'uses' => '',
) );
// EDD will set it's own defaults in the edd_store_discount() so let's filter out our own empty defaults (their just here for easier reference)
$meta = array_filter( $meta );
// EDD takes a $details array which has some different keys than the meta, let's map the keys to the expected format
$edd_post_keys = array(
'max_uses' => 'max',
'product_reqs' => 'products',
'excluded_products' => 'excluded-products',
'is_not_global' => 'not_global',
'is_single_use' => 'use_once'
);
foreach( $meta as $key => $value ) {
$mod_key = rgar( $edd_post_keys, $key );
if( $mod_key ) {
$meta[$mod_key] = $value;
}
}
edd_store_discount( $meta );
}
function is_applicable_form( $form ) {
$form_id = isset( $form['id'] ) ? $form['id'] : $form;
return $form_id == $this->_args['form_id'];
}
}
//* Instantiate the class for EDD
new GW_Create_Coupon( array(
'form_id' => ENGWP_FORM_ID,
'source_field_id' => ENGWP_SOURCE_FIELD_ID,
'amount' => ENGWP_DISCOUNT_AMOUNT,
'type' => ENGWP_DISCOUNT_TYPE,
'meta' => array(
'excluded_products' => array( ENGWP_EXCLUDE_PRODUCTS ),
'expiration' => $exp_date,
'is_not_global' => 'not_global',
'is_single_use' => ENGWP_SINGLE_USE,
'max_uses' => ENGWP_MAX_USES,
'min_price' => ENGWP_MIN_PRICE,
'product_condition' => ENGWP_REQS_CONDITION,
'product_reqs' => array( ENGWP_PRODUCT_REQS ),
'start' => $start_date,
)
) );
/**
* Generate the random codes to be used for the EDD discounts
*/
//* Generates and returns the code
add_filter( 'gform_field_value_uuid', 'gw_generate_unique_code' );
function gw_generate_unique_code() {
$length = ENGWP_CODE_LENGTH;
$chars = ENGWP_CODE_CHARS;
$prefix = ENGWP_CODE_PREFIX;
$unique = '';
$chars_length = strlen( $chars )-1;
for( $i = 0 ; $i < $length ; $i++ ) {
$unique .= $chars[ rand( 0, $chars_length ) ];
}
do {
$unique = $prefix . str_shuffle( $unique );
} while ( !gw_check_unique_code( $unique ) );
return $unique;
}
//* Checks to make sure the code generated is unique (not already in use)
function gw_check_unique_code( $unique ) {
global $wpdb;
$table = $wpdb->prefix . 'rg_lead_detail';
$form_id = ENGWP_FORM_ID; // update to the form ID your unique id field belongs to
$field_id = ENGWP_SOURCE_FIELD_ID; // update to the field ID your unique id is being prepopulated in
$result = $wpdb->get_var( "SELECT value FROM $table WHERE form_id = '$form_id' AND field_number = '$field_id' AND value = '$unique'" );
if ( empty ( $result ) ) {
return true;
} else return false;
}
You can use WC_Coupon to generate a coupon code. try the below code.
add_action( 'gform_after_submission', array( $this, 'create_coupon' ), 10, 2 );
public function create_coupon( $entry, $form ){
$coupon_code = rgar( $entry, $this->_args['source_field_id'] );
$date_expires = date('Y-m-d', strtotime('+14 days'));
$discount_type = 'fixed_cart'; // 'store_credit' doesn't exist
$coupon = new WC_Coupon();
$coupon->set_code($coupon_code);
//the coupon discount type can be 'fixed_cart', 'percent' or 'fixed_product', defaults to 'fixed_cart'
$coupon->set_discount_type($discount_type);
//the discount amount, defaults to zero
$coupon->set_amount($amount );
$coupon->set_date_expires( $date_expires );
//save the coupon
$coupon->save();
}

Trying show list of cities

First of all, sorry my horrible English =)
I'll try to explain how works everything:
I use this to create 'agreement' to be searched on my website, só the basic is the name, and where that 'agreement' works, for example, states and cities... but I have a problem when I try to select the 'states' and after show the cities to select where my 'agreement' can be used and save to show on the site.
But when I select the states, the WordPress just don't show the cities, and this problem happened after some att in WordPress plugins (exemple: Advanced custom field)
And know I have no idea how I can fix this.
Here is my code:
//Load cities - Convenio
function ag_apcef_load_cities_field_choices( $field ) {
// get selected
$selected = get_field( 'ag-estado-convenio', $post->ID );
// reset choices
$field['choices'] = array();
if($selected) {
$args = array(
'post_type' => 'cities',
'orderby' => 'title',
'order' => 'ASC',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'city_meta_box_state',
'value' => $selected->ID
)
)
);
$posts = get_posts( $args );
foreach($posts as $post) {
$field['choices'][$post->ID] = $post->post_title;
}
}
return $field;
}
add_filter('acf/load_field/name=ag-cidade-convenio', 'ag_apcef_load_cities_field_choices');
// Admin enqueue - Convenio
function ag_apcef_admin_convenio_enqueue( $hook ) {
// Allowed post types
$types = array( 'convenio' );
if( !in_array( get_post_type(), $types ) )
return;
wp_enqueue_script( 'populate-area', get_stylesheet_directory_uri() . '/js/autopopulate-admin.js' );
wp_localize_script( 'populate-area', 'populate_vars',
array(
'populate_nonce' => wp_create_nonce( 'populate_nonce' ), // Create nonce
)
);
}
add_action( 'admin_enqueue_scripts', 'ag_apcef_admin_convenio_enqueue' );
//Enqueue - Convenio
function ag_apcef_convenio_enqueue() {
if ( is_page( 'portal-de-vantagens' ) || is_page( 'bem-estar' )) {
wp_enqueue_script( 'populate-area', get_stylesheet_directory_uri() . '/js/autopopulate.js' );
wp_localize_script( 'populate-area', 'populate_vars',
array(
'populate_nonce' => wp_create_nonce( 'populate_nonce' ), // Create nonce
'ajaxurl' => admin_url( 'admin-ajax.php' )
)
);
}
}
add_action( 'wp_enqueue_scripts', 'ag_apcef_convenio_enqueue' );
// Load cities by state
function ag_apcef_city_by_state( $selected_state ) {
// Verify nonce
if( !isset( $_POST['populate_nonce'] ) || !wp_verify_nonce( $_POST['populate_nonce'], 'populate_nonce' ) )
die('Permission denied');
// Get selected state
$selected_state = $_POST['state'];
// Populate arr_data
$arr_data = array();
if(!empty($selected_state)) {
$args = array(
'post_type' => 'cities',
'orderby' => 'title',
'order' => 'ASC',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'city_meta_box_state',
'value' => $selected_state
)
)
);
$posts = get_posts( $args );
foreach($posts as $post) {
$arr_data[] = [
'key' => $post->ID,
'value' => $post->post_title
];
}
}
return wp_send_json($arr_data);
die();
}
add_action('wp_ajax_apcef_city_by_state', 'ag_apcef_city_by_state');
add_action('wp_ajax_nopriv_apcef_city_by_state', 'ag_apcef_city_by_state');

Adding ACF to CUSTOM wp api endpoints

I'm writing a custom endpoint for WP API, to retrieve posts from wordpress that for example are from the 'real_estate' post_type and capacity for '5 or more' persons.
I've built a new custom endpoint:
// permite que meta_key e meta_value
// sejam filtrados pela api
function filtros( $valid_vars ) {
$valid_vars = array_merge(
$valid_vars,
array(
'meta_key',
'meta_value' ) );
return $valid_vars;
}
add_filter( 'rest_query_vars', 'filtros' );
// funcção que retorna posts do autor
function busca( $data ) {
$posts = get_posts(array(
'post_type' => 'imoveis',
'posts_per_page' => '1000',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'transacao',
'value' => $data['tipo']
),
array(
'key' => 'quartos',
'value' => $data['quartos'],
'compare' => '>'
)
)
));
if ( empty( $posts ) ) {
return new WP_Error( 'sem resultados', 'quartos: ' . $data['quartos'] . ' transacao: '. $data['tipo'], array( 'status' => 404 ) );
}
return $posts;
}
// cria o endpoint que ira receber a função acima
add_action( 'rest_api_init', function () {
register_rest_route( 'busca/v2', '/resultado/(?P<tipo>.+)/(?P<quartos>\d+)',
array(
'methods' => 'GET',
'callback' => 'busca',
)
);
});
The search is fine, it's working, i'm filtering by transaction type (sale or rent) and number of rooms in each real estate.
But my JSON response is missing a lot of fields, including ACF.
EX:
{
"ID":149,
"post_author":"2",
"post_date":"2016-03-03 23:53:39",
"post_date_gmt":"2016-03-03 23:53:39",
"post_content":"",
"post_title":"Oportunidade do Ano",
"post_excerpt":"",
"post_status":"publish",
"comment_status":"closed",
"ping_status":"closed",
"post_password":"",
"post_name":"oportunidade-do-ano",
"to_ping":"",
"pinged":"",
"post_modified":"2016-03-03 23:53:39",
"post_modified_gmt":"2016-03-03 23:53:39",
"post_content_filtered":"",
"post_parent":0,
"guid":"http://raphaelk.co/api/?post_type=imoveis&p=149",
"menu_order":0,
"post_type":"imoveis",
"post_mime_type":"",
"comment_count":"0",
"filter":"raw"
},
Do you guys have any idea how can i change that response? And include ACF to it.
Thank you
Did you try to simply use the ACF function get_fields ?
In your "busca" function, after get_posts(), if $posts isn't empty, retrieve acf fields for each posts like this :
if ( empty( $posts ) ) {
return new WP_Error( 'sem resultados', 'quartos: ' . $data['quartos'] . ' transacao: '. $data['tipo'], array( 'status' => 404 ) );
} else {
foreach ($posts as $key => $post) {
$posts[$key]->acf = get_fields($post->ID);
}
}
Hopefully that'll do it !

If attribute's value is one thing, echo another in shortcode

Here's a shortcode of mine:
function sc_link( $atts ) {
extract( shortcode_atts(
array(
'page' => '',
'style' => 'button',
'window' => 'self',
'label' => 'Missing Label Tag: label=""',
), $atts )
);
return '' . $label . '';
}
add_shortcode( 'mylink', 'sc_link' );
What I want to be able to do is a conditional before the return: if $window = 'new' then echo 'blank'.
Think this is what your trying to do what id suggest doing is leaving window blank and just doing an if statement on that
How you want it
function sc_link( $atts ) {
extract( shortcode_atts(
array(
'page' => '',
'style' => 'button',
'window' => 'self',
'label' => 'Missing Label Tag: label=""',
), $atts )
);
if($window == "new"){
$link = '' . $label . '';
}else{
$link = '' . $label . '';
}
return $link;
}
add_shortcode( 'mylink', 'sc_link' );
How it should be
function sc_link( $atts ) {
extract( shortcode_atts(
array(
'page' => '',
'style' => 'button',
'window' => '',
'label' => 'Missing Label Tag: label=""',
), $atts )
);
if(!$window){
$link = '' . $label . '';
}else{
$link = '' . $label . '';
}
return $link;
}
add_shortcode( 'mylink', 'sc_link' );
The your shortcode will be link
[shorcode page="" window="" label=""]
Here is an easy short code conditional output example. I would recommend being sparing with this type of syntax because it can get lost in the fray.
echo ($window === 'new') ? $window : '';
This format is conditional ? what to do if true : what to do if false

Categories