Populate WordPress Advanced Custom Fields with remote JSON in backend - json

I have custom post types called "Products". and using the AFC(Advanced Custom Fields) plugin with this post type.
Below is what ACF has in fields group
- one filed called 'Product Description' as text area
- three text fields called 'Feature 1, Feature 2,Feature 3'
What I want to achieve is to get the data from external JSON file and populate the above ACF fields in the backend. I did some research and found Wordpress offers wp_remote_get() function to request the remote file. But I have no clue where to begin with to use this function or any other approach to use external JSON and populate these fields. Will really appreciate it someone points me to the right direction or any tutorial that shows how to achieve that. Thanks

I figured it out. View the working code below.
// Get JSON and Decode
$json_request = wp_remote_get( 'http://wp-test/test/data.json');
if( is_wp_error( $json_request ) ) {
return false;
}
$json_body = wp_remote_retrieve_body( $json_request );
$json_data = json_decode( $json_body );
// Create the new post and populate the fields
foreach( $json_data->products as $item ) {
$title = $item->title;
$desc = $item->content;
$status = $item->status;
$new_post = array(
'post_title' => $title,
'post_content' => $desc,
'post_status' => $status,
'post_author' => $userID,
'post_type' => 'products'
);
$post_id = post_exists( $title );
if (!$post_id) {
$post_id = wp_insert_post($new_post);
}
}

Related

Wordpress custom page template returns the theme headers

I want to return a JSON array from a Wordpress website. I know this can be done using plugins like WP REST API and JSON API, but I am dealing with custom post types so I want to avoid complexity and write the queries myself.
I have overridden one of my pages by writing a new php file in my theme directory called page-345.php.
Inside my PHP file I have the following code
$args = array(
'post_type' => 'partner',
'post_status' => 'publish',
'posts_per_page' => -1 // all
);
$query = new WP_Query( $args );
$cars = array();
while( $query->have_posts() ) : $query->the_post();
// Add a car entry
$cars[] = array(
'name' => get_the_title()
);
endwhile;
wp_reset_query();
wp_send_json( $cars );
I code works and I get output in JSON. However, JSON in returned alongside the header of the template. (See screenshot)
I also tried entering the code
header( 'Content-type: application/json' );
at the top of my page, but then Wordpress returns an error saying that headers have already been set.

ACF front end form to update term

I want to use ACF frontend form function to create a form with custom fields
I see this issue for create new term, #Alhana
ACF front end form to create term
but I want to generate the form with old data
Well, i didn't see that question, but if it's still actual, here's a solution.
First of all, make sure you have ACF group, linked to your taxonomy. You will need ID of this group, it can be found in url on group edit page, for example:
http://site.ru/wp-admin/post.php?post=340&action=edit
In this case group ID is 340. If you don't want to use hardcoded ID (if your groups are changing from time to time), you can get it, using group name (in this example group name is Technic CPT):
global $wpdb;
$group_ID = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_title = 'Technic CPT'" );
Then, you'll need ID of term you're updating. I think, it's not nesessary to write about getting it since it's WP basics :) You'll end with something like this:
$term_id = 405;
And finally, you'll need your taxonomy's slug. In this example it's technic. So, let's render our form!
acf_form_head();
$acf_form_args = array(
'id' => 'technic_edit_form',
'post_id' => 'technic_'.$term_id,
'form' => true,
'submit_value' => 'Update technic',
'field_groups' => array($group_ID),
'updated_message' => 'Technic is updated!';
);
acf_form( $acf_form_args );
Now your term's custom fields will be shown in this form. But to save term data after editing you'll need to add some more code. ACF form assumes that you're saving post data, we'll add some logic to detect saving data for term.
add_filter( 'acf/pre_save_post', 'acf_handle_form_save', 10, 1 );
function acf_handle_form_save( $post_id ) {
// Function accepts id of object we're saving.
// All WordPress IDs are unique so we can use this to check which object it is now.
// We'll try to get term by id.
// We'll get term id with added taxonomy slug, for example 'technic_405'.
// For checking term existence we must cut out this slug.
$cut_post_id = str_replace( 'technic_', '', $post_id );
$test_tax_term = get_term_by( 'id', $cut_post_id, 'technic' );
// If $test_tax_term is true - we are saving taxonomy term.
// So let's change form behaviour to saving term instead of post.
if ( $test_tax_term ) :
// Get array of fields, attached to our taxonomy
global $wpdb;
$group_ID = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_title = 'Technic CPT'" );
$acf_fields = acf_get_fields_by_id( $group_ID );
// Then sanitize fields from $_POST
// All acf fields will be in $_POST['acf']
foreach ( $acf_fields as $acf_field ) :
$$acf_field[ 'name' ] = trim( esc_attr( strip_tags( $_POST[ 'acf' ][ $acf_field[ 'key' ] ] ) ) );
endforeach;
// We need to have some fields in our group, which are just duplicates of standard term fields: name, slug, description.
// In this example it's only one field - term name, called 'technic_name'.
$name = 'technic_name';
// Update base term info, in this example - only name.
$term = wp_update_term( $cut_post_id, 'technic', array( 'name' => $$name ) );
// If all is correct, update custom fields:
if ( !is_wp_error( $term ) ) :
foreach ( $acf_fields as $acf_field ) :
update_field( $acf_field[ 'name' ], $$acf_field[ 'name' ], 'technic_' . $cut_post_id );
endforeach;
endif;
else :
// Here is saving usual post data. Do what you need for saving it or just skip this point
endif;
return $post_id;
}
Please note: validation of $_POST data may be more complex. For example, you may have to validate array of values if there are ACF galleries or relationships among your taxonomy fields. In my example i have only common text fields.
Hope that helps!
The answer from Alhana worked for me with one change. The term object works if sent as the the value for the post_id:
$term_obj = get_term($term_id);
$acf_form_args = array(
'post_id' => $term_obj,
'post_title' => false,
'submit_value' => 'Update Term',
'field_groups' => array($group_ID),
);

cakephp : getting pagination link in json format

I am developing a REST API using CakePHP and want to implement the Instagram API pagination style which looks something like this:
{
...
"pagination": {
"next_url": "https://api.instagram.com/v1/tags/puppy/media/recent?access_token=fb2e77d.47a0479900504cb3ab4a1f626d174d2d&max_id=13872296",
"next_max_id": "13872296"
}
}
I have not used any authorization or whatever, so the access_token part can be ignored. My main motive is to get the pagination links (jump links preferably) as JSON data, so I can use it in my JSON serialized view. Because the usual code:
echo $this->Paginator->prev('< ' . __('previous'), array(), null, array('class' => 'prev disabled'));
echo $this->Paginator->numbers(array('separator' => ''));
echo $this->Paginator->next(__('next') . ' >', array(), null, array('class' => 'next disabled'));
doesn't work and simply displays the equivalent HTML code.
Is there any way I can get it like the Instagram API?
Thanks to noslone, i have got the answer. here is the final edited code:
$url = 'http://yourapp.com/pages/index/limit:7';
$returnArray = array(
.....
'pagination' => array(
'next_url' => null,
'prev_url' => null
)
);
if($this->Paginator->hasNext()) {
$temp = intval($this->Paginator->current())+1;
$returnArray['pagination']['next_url'] = $url."/page:".$temp;
}
if($this->Paginator->hasPrev()) {
$temp = intval($this->Paginator->current())-1;
$returnArray['pagination']['next_url'] = $url."/page:".$temp;
}
echo json_encode($returnArray);
just two changes : first don't forget to add limit:value" to your url and secondly use intval with the Paginator->current.
Try something as follow
$url = 'http://yourapp.com/pages/index';
$returnArray = array(
.....
'pagination' => array(
'next_url' => null,
'prev_url' => null
)
);
if($this->Paginator->hasNext()) {
$returnArray['pagination']['next_url'] = $url.'/page:'. ($this->Paginator->current()+1);
}
if($this->Paginator->hasPrev()) {
$returnArray['pagination']['prev_url'] = $url.'/page:'. ($this->Paginator->current()-1);
}
echo json_encode($returnArray);
If you want, you can add more named params to the url:
$params['pagination']['next_url'] = $url.'/page:'.$this->Paginator->current()+1.'/order:name/direction:asc';
As far as I know, Paginator helper generates the front-end link, and when you click on it, it will generate next link.
I do not think you can use it directly to form the Instagram alike API.

How can I insert data from a table from sql into a dropdown list in zend framework 2?

I need to insert multioptions to a dropdown list, options taken from a table from my database.
I created the elements like:
$this->add(array(
'name' => 'company',
'type' => 'Zend\Form\Element\Select',
//'multiOptions'=> $options,
'options' => array(
'label' => 'Company',
),
'attributes' => array(
'style' => "float:right;",
),
));
I want to choose from a dropdown list some values that are in a table in my database. For example I have the entity Contacts and I need to choose for the contact a company that is in a table named companies in the database.
After reading on zend framework's site, I tried using this code:
$params = array(
'driver'=>'Pdo_Mysql',
'host'=>'localhost',
'username'=>'root',
'password'=>'',
'dbname' =>'myDataBase'
);
$db = new \Zend\Db\Adapter\Adapter($params);
$sql= new Sql($db);
$select = $sql->select();
$select ->from('companies')
->columns(array('id','company_name'))
->order(" 'company_name' ASC");
I also read on some other sites that I could use a function:
$options = $sql->fetchPairs('SELECT id, name FROM country ORDER BY name ASC');
but it seems it doesn't exist anymore in Zend Framework 2.
Please guys, give me a hand. If the code isn't good and you have a better idea, please tell me.
Thanks in advance!
This is just a quick and dirty answer, but i guess it can get you started.
Create a ServiceFactory, this should be done in a separate factory class instead of a closure, but i still use a closure - faster to write ;)
Get the config from the ServiceLocator so you have access to the DB-Params
Create your default SQL Stuff to retriefe the value_options
Populate the value_options using the setValueOptions($valueOptions) function of your given form-element
Module.php getServiceConfig()
return array(
'factories' => array(
'my-form-factory' => function($serviceLocator) {
$form = new My\Form();
$config = $serviceLocator->get('config');
$db = new \Zend\Db\Auth\Adapter\Adapter($config['dbParams']); //or whatever you named the array key
$sql = //do your SQL Stuff
// This is a fake array, it should be your $sql result in the given format
$result = array('value' => 'label', 'value2' => 'label2');
$form->get('elementToPopulate')->setValueOptions($result);
return $form;
}
)
);
SomeController.php someAction()
$form = $this->getServiceLocator()->get('my-form-factory');
return new ViewModel(array(
'form' => $form
));
I hope this gets you started
you have to add that field validation on controller for setting value in it.
$select = $db->select()->where("state_code = ?",$arr["state_code"]);
$resultSet = $cityObj->fetchAll($select);
$cityArr = $resultSet->toArray();
$city_ar = array();
foreach($cityArr as $city){
$city_ar[$city['id']] = $city['company'];
}
$form->company->setMultiOptions($city_ar);
$form->company->setValue($val["company"]);
by using this code drop down of country have the value that are in resultset array ($resultSet).

Parsing External Table Arguments in Wordpress

I have a client project that has posts assigned to their country of origin.
The client wants to be able to search the posts by continent and or region.
I have a separate table that assigns each country to its respective region, and I have the WP query that uses the resulting array:
$country_names = array('England','France','Germany',...); // this would be the result from fetching countries associated with a region.
$args = array(
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'country',
'value' => $country_names,
'compare' => 'IN'
)
)
);
$query = new WP_Query( $args );
What I'm having trouble with is the part in the middle. Normally, I'd use some standard PHP/MySQL to craft the array:
<?php
//Process incoming variable
if(!empty($_REQUEST['region'])){
$region = $_REQUEST['region'];
} else {
$region = NULL;
}
// Make a MySQL Connection
$query = "SELECT * FROM regions WHERE region='$region'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
echo $row['country'];
?>
However, I'm having trouble making it work within a WP template, since WP manages the incoming variables using its own internal functions.
Can anyone help me to connect the two together? I'm sure I'm overlooking some simple step here, or else I'm not using some built-in WP function.
Any help is appreciated.
Thanks!
ty
Add this in your functions.php
add_filter( 'query_vars', 'addnew_query_vars', 10, 1 );
function addnew_query_vars($vars)
{
$vars[] = 'region'; // region is the variable you want to add
$vars[] = 'anotherVar';
return $vars;
}
Then get it
$region=get_query_var('region')
Update
$regions = $wpdb->get_results("SELECT ".$region." FROM `".$wpdb->regions."`");
if($regions)
{
foreach($regions as $region)
{
// your code
}
}