Trying show list of cities - php

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');

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
]
] );
}

WooCommerce using meta_query to get products where custom checkbox option is NOT checked

I have built a WooCommerce website for a client with a "Latest Products" page. Due to the competitive nature of the client's industry, the client wants to be able to select certain products to NOT appear amongst the Latest Products.
For this, I have added a custom "Hide from Latest Products" checkbox to the product editor with this code:
add_action('add_meta_boxes', 'gd_add_product_extra_options_metabox');
function gd_add_product_extra_options_metabox(){
add_meta_box("product_extra_options_meta", "Extra Options", "gd_product_extra_options_metabox", "product", "side", "high");
}
// ADD CUSTOM FIELDS //
function gd_product_extra_options_metabox(){
global $post;
// Nonce field to validate form request came from current site
wp_nonce_field( basename( __FILE__ ), 'product_fields' );
// Get the field data if it's already been entered
$hide_from_latest = get_post_meta( $post->ID, 'hide_from_latest', true );
if($hide_from_latest == '1'){$checked = ' checked';}else{$checked = '';}
// Output the field
echo '<p><input type="checkbox" name="hide_from_latest" value="1"' . $checked . '> Hide from Latest Products</p>';
}
And so on and so forth with the saving code, etc. The checkbox appears to work perfectly.
The problem though, is in writing a custom product query to fetch all of the latest products for which this checkbox is NOT checked.
For testing, I have checked and saved the "Hide" option for only 1 product.
I have my query as follows:
$products = new WP_Query( array (
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => '100',
'order_by' => 'date',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'hide_from_latest',
'value' => '1',
'compare' => 'NOT LIKE'
),
)
This gives me a very empty screen with "There is no results."
If, however, I change the meta_query to:
'meta_query' => array(
array(
'key' => 'hide_from_latest',
'value' => '1',
'compare' => 'LIKE'
),
)
Then it fetches and displays the 1 single product that I have checked and saved the option for.
I have tried various other options such as using "=" and "!=" for 'compare', I've tried changing the value of the checkbox to "on" and then having 'value' => 'on' in the meta_query, etc. The results are always the same.
Where have I gone wrong?
EDIT:
Here is my full code:
// ADD CUSTOM OPTIONS TO WOOCOMMERCE PRODUCTS //
add_action('add_meta_boxes', 'gd_add_product_extra_options_metabox');
function gd_add_product_extra_options_metabox(){
add_meta_box("product_extra_options_meta", "Extra Options", "gd_product_extra_options_metabox", "product", "side", "high");
}
// ADD CUSTOM FIELDS //
function gd_product_extra_options_metabox(){
global $post;
// Nonce field to validate form request came from current site
wp_nonce_field( basename( __FILE__ ), 'notice_fields' );
// Get the field data if it's already been entered
$hide_from_latest = get_post_meta( $post->ID, 'hide_from_latest', true );
if($hide_from_latest == '1'){$checked = ' checked';}else{$checked = '';}
// Output the field
echo '<p><input type="checkbox" name="hide_from_latest" value="1"' . $checked . '> Hide from Latest Products</p>';
}
// SAVE METABOX DATA //
function gd_save_product_extra_options_metabox( $post_id, $post ) {
// Return if the user doesn't have edit permissions.
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return $post_id;
}
// Verify this came from the our screen and with proper authorization,
// because save_post can be triggered at other times.
if ( !wp_verify_nonce($_POST['notice_fields'], basename(__FILE__)) ) {
return $post_id;
}
// Now that we're authenticated, time to save the data.
// This sanitizes the data from the field and saves it into an array $product_meta.
$product_meta['hide_from_latest'] = esc_textarea( $_POST['hide_from_latest'] );
// Cycle through the $notice_meta array.
foreach ( $product_meta as $key => $value ) :
// Don't store custom data twice
if ( 'revision' === $post->post_type ) {
return;
}
if ( get_post_meta( $post_id, $key, false ) ) {
// If the custom field already has a value, update it.
update_post_meta( $post_id, $key, $value );
} else {
// If the custom field doesn't have a value, add it.
add_post_meta( $post_id, $key, $value);
}
if ( ! $value ) {
// Delete the meta key if there's no value
delete_post_meta( $post_id, $key );
}
endforeach;
}
add_action( 'save_post', 'gd_save_product_extra_options_metabox', 1, 2 );
if( ! function_exists('latest_products_censored') ) {
// Add Shortcode
function latest_products_censored( $atts ) {
global $woocommerce_loop;
// Attributes
$atts = shortcode_atts(
array(
'columns' => '4',
'limit' => '100'
),
$atts, 'products_test'
);
$woocommerce_loop['columns'] = $atts['columns'];
// The WP_Query
$products = new WP_Query( array (
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => $atts['limit'],
'order_by' => 'date',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'hide_from_latest',
'value' => '1',
'compare' => 'NOT LIKE'
),
)
));
ob_start();
if ( $products->have_posts() ) { ?>
<?php woocommerce_product_loop_start(); ?>
<?php while ( $products->have_posts() ) : $products->the_post(); ?>
<?php wc_get_template_part( 'content', 'product' ); ?>
<?php endwhile; // end of the loop. ?>
<?php woocommerce_product_loop_end(); ?>
<?php
} else {
do_action( "woocommerce_shortcode_products_loop_no_results", $atts );
echo "<p>There is no results.</p>";
}
woocommerce_reset_loop();
wp_reset_postdata();
return '<div class="woocommerce columns-' . $atts['columns'] . '">' . ob_get_clean() . '</div>';
}
add_shortcode( 'latest_products_censored', 'latest_products_censored' );
}
After a bit more digging in the Wordpress Codex, I have found the answer!
The meta_query needs to be:
'meta_query' => array(
array(
'key' => 'hide_from_latest',
'value' => '1',
'compare' => 'NOT EXISTS'
),
)
I have just given that a go and it is now working perfectly! :-)

Wordpress custom post type & custom taxonomy reset (performance issue)

I developed a plugin that reads a csv file in order to create 4 different custom taxonomies (Categories) and 1 custom post type (Post) using PHP and WordPress.
On the Initial import the execution time is less than 6 seconds, however the second time execution takes more than 1 minute in order to reset and re-upload the data.
The issue that I found is on the resetAllPosts function (see code)
public function resetAllPosts() {
$query = new WP_Query( array(
'post_type' => 'psp',
'post_status' => 'publish',
'posts_per_page' => 100
) );
// remove all taxonomies will take too long..
// delete all custom taxonomies terms
$terms_payment = get_terms( 'payment', array( 'fields' => 'ids', 'hide_empty' => false ) );
$terms_country = get_terms( 'country', array( 'fields' => 'ids', 'hide_empty' => false ) );
$terms_currency = get_terms( 'currency', array( 'fields' => 'ids', 'hide_empty' => false ) );
$terms_provider = get_terms( 'provider', array( 'fields' => 'ids', 'hide_empty' => false ) );
foreach ( $terms_payment as $value ) {
wp_delete_term( $value, 'payment' );
}
foreach ( $terms_country as $value ) {
wp_delete_term( $value, 'country' );
}
foreach ( $terms_currency as $value ) {
wp_delete_term( $value, 'currency' );
}
foreach ( $terms_provider as $value ) {
wp_delete_term( $value, 'provider' );
}
while ( $query->have_posts() ) {
$query->the_post();
$post_id = get_the_ID();
// remove the relation between the post and the taxonomies
//wp_delete_object_term_relationships(get_the_ID(),array("provider","payment","currency","country"));
// Remove the feature image from Media gallery
//$post_thumbnail_id = get_post_thumbnail_id( $post_id );
//wp_delete_attachment( $post_thumbnail_id, true );
// delete the post
wp_delete_post( $post_id, "true" );
}
echo "Reset of all data success..";
}
I would like to know the best/fastest way to delete all terms data.

wordpress add field for every custom type

I want to create a stock level field in WooCommerce Products for every Store custom post type.
I've already created the Store custom post type and added 3 stores to it. I want to automatically add a "stock level at store" field every time someone adds a Store so that I could check the stocks at store level.
I'm trying to put the custom field at the Products->Inventory-> right under the Stock Quantity.
I've tried this:
$post_type = 'store';
$tax = 'show-topic';
$inv_arg_terms = get_terms(array('orderby' => 'id', 'order' => 'ASC'));
if ($inv_arg_terms) {
$args = array(
'post_type' => $post_type,
'post_status' => 'publish',
'posts_per_page' => - 1,
'orderby' => 'title',
'order' => 'ASC'
); // END $args
$my_query = null;
$my_query = new WP_Query($args);
if ($my_query->have_posts()) {
while ($my_query->have_posts()) : $my_query->the_post();
add_action( 'woocommerce_product_options_inventory_product_data', 'wc_inventory_stock_product_field' );
function wc_inventory_stock_product_field() {
woocommerce_wp_text_input( array( 'id' => 'stock_level_' . the_title(), 'class' => 'short wc_input_stock', 'label' => __( 'Stock Level at ' . the_title(), 'woocommerce' ) . ' (' . get_woocommerce_currency_symbol() . ')' ) );
}
add_action( 'save_post', 'wc_cost_save_product' );
function wc_cost_save_product( $product_id ) {
// stop the quick edit interferring as this will stop it saving properly, when a user uses quick edit feature
if (wp_verify_nonce($_POST['_inline_edit'], 'inlineeditnonce'))
return;
// If this is a auto save do nothing, we only save when update button is clicked
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
if ( isset( $_POST['stock_level_' . the_title()] ) ) {
if ( is_numeric( $_POST['stock_level_' . the_title()] ) )
update_post_meta( $product_id, 'stock_level_' . the_title(), $_POST['cost_price'] );
} else delete_post_meta( $product_id, 'stock_level_' . the_title() );
}
endwhile;
} // END if have_posts loop
wp_reset_query();
} // END if $inv_arg_terms
and I got this:
Fatal error: Call to undefined function get_userdata() in
.../wp-includes/query.php on line 4758
Is what I'm thinking possible? How do I go about it?
Thanks, appreciate every help I could get.
Finally got it to work. Here's the code:
add_action( 'woocommerce_product_options_inventory_product_data', 'wc_stock_product_field' );
add_action( 'woocommerce_process_product_meta', 'wc_stock_save_product' );
function wc_stock_product_field() {
global $woocommerce, $post;
$post_type = 'store';
$args = array(
'post_type' => $post_type,
'post_status' => 'publish',
'posts_per_page' => - 1,
'orderby' => 'id',
'order' => 'ASC',
'caller_get_posts' => 1
); // END $args
$store_query = null;
$store_query = new WP_Query($args);
if ($store_query->have_posts()) {
while ($store_query->have_posts()) : $store_query->the_post();
woocommerce_wp_text_input(
array(
'id' => get_the_id() ,
'class' => 'short wc_input_stock',
'label' => __( 'Stock Level # ' . get_the_title(), 'woocommerce' ) ) );
endwhile;
} // END if have_posts loop
wp_reset_query();
}
function wc_stock_save_product( $product_id ) {
// stop the quick edit interferring as this will stop it saving properly, when a user uses quick edit feature
if (wp_verify_nonce($_POST['_inline_edit'], 'inlineeditnonce'))
return;
// If this is a auto save do nothing, we only save when update button is clicked
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
$post_type = 'store';
$args = array(
'post_type' => $post_type,
'post_status' => 'publish',
'posts_per_page' => - 1,
'orderby' => 'id',
'order' => 'ASC',
'caller_get_posts' => 1
); // END $args
$store_query = null;
$store_query = new WP_Query($args);
if ($store_query->have_posts()) {
while ($store_query->have_posts()) : $store_query->the_post();
if ( isset( $_POST[get_the_id()] ) ) {
if ( is_numeric( $_POST[get_the_id()] ) )
update_post_meta( $product_id, get_the_id(), $_POST[get_the_id()] );
} else delete_post_meta( $product_id, get_the_id() );
endwhile;
} // END if have_posts loop
wp_reset_query();
}

Custom post type not showing posts inserted from frontend

Hey everyone,
I have a post type called `index`, and i'm trying to build a form for users to insert posts from the frontend.
i created a page and a template for it with a form and an ajax function which insert the content to the DB using `wp_insert_post`. the function works generally, i can see the new posts added to the wp_post db in phpmyadmin. the problem is that i can't see the new posts in the admin panel. the post are counted (i can see the number goes up everytime i try the form), but not shown.
this is the functions.php ajax code (some $_get vars are to be used for meta data inserting):
add_action('wp_ajax_addtoindex', 'addtoindex');
add_action('wp_ajax_nopriv_addtoindex', 'addtoindex');
function addtoindex(){
$title = $_GET["title"];
$slug = sanitize_title_with_dashes($title,'','save');
$group = $_GET["group"];
$inst = $_GET["inst"];
$location = $_GET["location"];
$address = $_GET["address"];
$content = $_GET["content"];
$website = $_GET["website"];
$year = $_GET["year"];
$educ = $_GET["educ"];
$aud = $_GET["aud"];
$teaching = $_GET["teaching"];
$teachers = $_GET["teachers"];
$contact1 = $_GET["contact1"];
$email1 = $_GET["email1"];
$phone1 = $_GET["phone1"];
$contact2 = $_GET["contact2"];
$email2 = $_GET["email2"];
$phone2 = $_GET["phone2"];
$user = get_user_by("login",$authorid);
$authorid = $user->ID;
// Check if the group exists
$group_term = term_exists( $group, 'group', 0 );
// Create group if it doesn't exist
if ( !$group_term ) {
$group_term = wp_insert_term( $group, 'group', array( 'parent' => 0 ) );
}
// Check if the inst exists
$inst_term = term_exists( $inst, 'inst', 0 );
// Create inst if it doesn't exist
if ( !$inst_term ) {
$inst_term = wp_insert_term( $inst, 'inst', array( 'parent' => 0 ) );
}
// Check if the location exists
$location_term = term_exists( $location, 'location', 0 );
// Create location if it doesn't exist
if ( !$location_term ) {
$location_term = wp_insert_term( $location, 'location', array( 'parent' => 0 ) );
}
$custom_tax = array(
'group' => $group_term,
'inst' => $group_inst,
'location' => $group_location
);
//Post Properties
$new_post = array(
'post_title' => $title,
'post_name' => $slug,
'post_content' => $content,
'post_status' => 'pending',
'post_type' => 'index',
'post_author' => $authorid,
'comment_status' => 'closed',
'ping_status' => 'closed',
'tax_input' => $custom_tax
);
//save the new post
if ( post_type_exists( 'index' ) ) {
$pid = wp_insert_post($new_post, true);
echo 'good';
}
else{
echo "bad";
}
// Reset Post Data
wp_reset_postdata();
exit;
}
and this is the index post type code:
function post_type_index() {
register_post_type( 'index',
array(
'label' => __('Index'),
'labels' => array('name' => 'אינדקס האנתרופוסופיה','singular_name' => __('פריט לאינדקס','ohav'),'edit_item' => __('עריכת פריט אינדקס','ohav'),'add_new' => __('הוספת פריט לאינדקס','ohav'),'add_new_item' => __('הוספת פריט לאינדקס','ohav'),'all_items' => __('לכל פריטי האינדקס','ohav')),
'public' => true,
//'publicly_queryable' => true,
//'query_var' => true,
//'capability_type' => 'post',
'has_archive' => true,
'show_ui' => true,
'show_in_nav_menus' => true,
'rewrite' =>array(
'slug' => __('index','ohav'),
'with_front' => true
),
'hierarchical' => true,
'supports' => array(
'title',
'boxplace',
'editor',
'thumbnail'
)
)
);
}
add_action('init', 'post_type_index');
okay i found it!
the problem was i already had a pre_get_posts hook that changes the order of the index archive according to the post meta.
add_action( 'pre_get_posts', 'change_order_for_index' );
function change_order_for_index( $query ) {
if ( is_post_type_archive('index') ) {
$query->set( 'meta_key', '_index_featured' );
$query->set( 'orderby', 'meta_value' );
}
}
i added && !is_admin() to the if and it turned okay.
thank you Arif, your answer helped me find it.
you can add an action hook 'pre_get_posts' to include/exclude your custom post type to/from the admin post list or any for any other listing like archives.
add_filter( 'pre_get_posts', 'include_custom_type_index' );
function include_custom_type_index( $query ) {
$query->set( 'post_type', array(
'post', 'index'
));
return $query;
}

Categories