How to use ACF into JSON via ajax in Wordpress - json

I'm trying to use the Advanced Custom Field (ACF) plugin to return JSON via ajax in WordPress.
The below code correctly returns the JSON data of the posts but is not giving me the ACF data inside each post.
How can I get that ACF data into JSON?
PHP File
add_shortcode("owt-ajax-shortcode", "owt_wpl_run_shortcode");
function owt_wpl_run_shortcode() {
ob_start();
include_once plugin_dir_path(__FILE__) . 'views/owt-ajax-page-view.php';
$template = ob_get_contents();
ob_end_clean();
echo $template;
}
add_action("wp_enqueue_scripts", "owt_include_scripts");
function owt_include_scripts() {
wp_enqueue_script("jquery");
}
add_action("wp_ajax_owt_ajax_lib", "owt_lib_ajax_handler_fn");
add_action("wp_ajax_nopriv_owt_ajax_lib", "owt_lib_ajax_handler_fn");
function owt_lib_ajax_handler_fn() {
$param = isset($_REQUEST['param']) ? trim($_REQUEST['param']) : "";
global $wpdb;
if (!empty($param)) {
if ($param == "get_all_posts") {
$all_posts = get_posts(array(
"post_type" => "post",
"post_status" => "publish",
'posts_per_page' => 20,
'order' => 'DESC',
'orderby' => 'date',
'cat' => 66
));
header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );
echo json_encode( $all_posts );
die;
}
}
wp_die();
}
JavaScript
<button id="btn-get-all-posts">Click to get All Posts</button>
<script>
jQuery(function () {
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
jQuery("#btn-get-all-posts").on("click", function () {
var postdata = "action=owt_ajax_lib&param=get_all_posts";
jQuery.post(ajaxurl, postdata, function (response) {
console.log(response);
});
});
});
</script>

instead of use get_posts try your own query with WP_Query
here is an example code, please let me know if it works correctly(I didn't test it yet)
function owt_lib_ajax_handler_fn()
{
$param = isset($_REQUEST[ 'param' ]) ? trim($_REQUEST[ 'param' ]) : "";
if ( ! empty($param) ){
if ( $param == "get_all_posts" ){
$args = [
"post_type" => "post",
"post_status" => "publish",
"posts_per_page" => 20,
"order" => 'DESC',
"orderby" => 'date',
"category__in" => [ 66 ],
];
$all_posts = new WP_Query($args);
$json_response = [];
if ( $all_posts->have_posts() ){
while ( $all_posts->have_posts() ) {
$json_response[] = [
'title' => get_the_title(),
'content' => get_the_content(),
'acf_meta' => [
get_fields(get_the_ID()),
],
];
}
wp_send_json($json_response, 200);
wp_die();
}
else {
wp_send_json($json_response, 404);
wp_die();
}
}
}
wp_die();
}

please have a look as below:
$posts = get_posts(array(
'numberposts' => -1,
'post_type' => 'post',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'color',
'value' => array('red', 'orange'),
'compare' => 'IN',
),
array(
'key' => 'featured',
'value' => '1',
'compare' => '=',
),
),
));

Please use below function:
add_action("wp_ajax_owt_ajax_lib", "owt_ajax_lib");
add_action("wp_ajax_nopriv_owt_ajax_lib", "owt_ajax_lib");
function owt_ajax_lib() {
$param = isset($_REQUEST['param']) ? trim($_REQUEST['param']) : "";
global $wpdb;
if (!empty($param)) {
if ($param == "get_all_posts") {
$args = [
"post_type" => "post",
"post_status" => "publish",
"posts_per_page" => 20,
"order" => 'DESC',
"orderby" => 'date',
"category__in" => [ 33 ],
];
$all_posts = new WP_Query($args);
$json_response = array();
if ( $all_posts->have_posts() ):
while ( $all_posts->have_posts() ) : $all_posts->the_post();
$json_response[] = [
'title' => get_the_title(),
'content' => get_the_content(),
'acf_meta' => [
get_fields( get_the_ID() ),
],
];
endwhile;
endif;
echo json_encode($json_response);
die;
}
}
die;
}

Related

wp_remote_post() body empty

I am trying to build a plugin that sends webhooks to an external site from client sites so I can keep a record of everything that happens from when a user signs in, to when someone installs a new plugin or updates or adds new pages etc.
The problem is I am receiving NULL values through the $api array, and can't seem to figure it out.
This is my last attempt and making this work:
function send_webhook_on_plugin_install( $install_result, $package, $api ) {
$webhook_url = 'https://example.com';
$installed_plugins = get_plugins();
$installed_plugins = array_keys( $installed_plugins );
$new_plugin = false;
$new_plugin_name = '';
$new_plugin_version = '';
foreach ( $installed_plugins as $installed_plugin ) {
if ( ! in_array( $installed_plugin, $package ) ) {
$new_plugin = $installed_plugin;
break;
}
}
if ( $new_plugin ) {
$new_plugin_data = get_plugins( '/' . $new_plugin );
$new_plugin_name = $new_plugin_data[ $new_plugin ]['Name'];
$new_plugin_version = $new_plugin_data[ $new_plugin ]['Version'];
}
$body = array(
'plugin_name' => $new_plugin_name,
'plugin_version' => $new_plugin_version
);
$response = wp_remote_post( $webhook_url, array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array( 'Content-Type' => 'application/json' ),
'body' => wp_json_encode( $body ),
'cookies' => array()
) );
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
// Log the error
error_log( "Webhook failed: $error_message" );
}
}
add_action( 'upgrader_post_install', 'send_webhook_on_plugin_install', 10, 3 );
The JSON that is being received is:
{
"plugin_name": null,
"plugin_version": null
}
The Warnings I'm getting are this:
PHP Warning: Undefined array key "advanced-custom-fields-pro/acf.php" in C:\xampp\htdocs\site\wp-content\plugins\webhook-sender\plugin-update.php on line 25
PHP Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\site\wp-content\plugins\webhook-sender\plugin-update.php on line 25
Previous Versions of the code that also failed:
function send_webhook_on_plugin_install( $install_result, $package, $api ) {
$webhook_url = 'https://example.com';
$body = array(
'plugin_name' => $api['name'],
'plugin_version' => $api['version']
);
$response = wp_remote_post( $webhook_url, array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array( 'Content-Type' => 'application/json' ),
'body' => wp_json_encode( $body ),
'cookies' => array()
) );
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
// Log the error
error_log( "Webhook failed: $error_message" );
}
}
add_action( 'upgrader_post_install', 'send_webhook_on_plugin_install', 10, 3 );
I thought by accessing $api array directly might work, but still getting NULL values on the return.
and...
function send_webhook_on_plugin_install( $install_result, $package, $api ) {
$webhook_url = 'https://example.com';
$body = array(
'plugin_name' => $api->name,
'plugin_version' => $api->version
);
$response = wp_remote_post( $webhook_url, array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array( 'Content-Type' => 'application/json' ),
'body' => wp_json_encode( $body ),
'cookies' => array()
) );
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
// Log the error
error_log( "Webhook failed: $error_message" );
}
}
add_action( 'upgrader_post_install', 'send_webhook_on_plugin_install', 10, 3 );

How to apply pagination for custom endpoint request in wordpress?

I have created a custom restful API endpoint in WordPress which returns the JSON with the only required fields.
So with this one when I go to the example.com/wp-json/wl/posts, it returns 5 posts as I have limited the number of the posts.
function wl_posts() {
$args = [
'numberposts' => 99999,
'post_type' => 'post'
];
$posts = get_posts($args);
$data = [];
$i = 0;
foreach($posts as $post) {
$data[$i]['id'] = $post->ID;
$data[$i]['title'] = $post->post_title;
$data[$i]['content'] = $post->post_content;
$data[$i]['slug'] = $post->post_name;
$data[$i]['featured_image']['thumbnail'] = get_the_post_thumbnail_url($post->ID, 'thumbnail');
$i++;
}
return $data;
}
add_action('rest_api_init', function() {
register_rest_route('wl/v1', 'posts', [
'methods' => 'GET',
'callback' => 'wl_posts',
]);
});
But I also want to add the pagination, so if I add ?page=2 , it should return another 5 posts.
How can that be archived?
When visiting /?rest_route=/ or /wp-json/wp/v2/pages you can drill down into ie. wp/v2/pages/endpoints/0/args then check with page and per_page
curl http://YOUR-SITE/wp-json/wl/v1/posts/?per_page=1&page=2
Publish arguments for reference
We can define and publish these as arguments. This is not required but they are now in line with posts and pages
add_action('rest_api_init', function() {
register_rest_route('wl/v1', 'posts', [
'methods' => 'GET',
'callback' => 'wl_posts',
'args' => [
'page' => [
'description' => 'Current page',
'type' => "integer",
],
'per_page' => [
'description' => 'Items per page',
'type' => "integer",
]
],
]);
});
Fetch arguments
As get_posts has its own logic and it uses WP_Query in the end let's use WP_Query for the better.
function wl_posts() {
$args = [];
if (isset($_REQUEST['per_page'])) {
$args['posts_per_page'] = (int) $_REQUEST['per_page'];
}
if (isset($_REQUEST['page'])) {
$args['page'] = (int) $_REQUEST['page'];
}
$args['post_type'] = 'post';
$get_posts = new WP_Query;
$posts= $get_posts->query( $args );
$data = [];
$i = 0;
foreach($posts as $post) {
$data[$i]['id'] = $post->ID;
$data[$i]['title'] = $post->post_title;
$data[$i]['content'] = $post->post_content;
$data[$i]['slug'] = $post->post_name;
$data[$i]['featured_image']['thumbnail'] =
get_the_post_thumbnail_url($post->ID, 'thumbnail');
$i++;
}
return $data;
}

PHP - Yii 2.0 Multiple images are save in folder but not saved in database

I have used use kartik\file\FileInput; (extension) for saving multiple images from single form submit.
The images are save locally but are not saving in the database.
Here is my Model Code media.php
namespace app\models;
use yii\web\UploadedFile;
class Media extends \yii\db\ActiveRecord
{
public function rules(){
return [
[['title'], 'file', 'skipOnEmpty' => false, 'extensions' => ['gif', 'jpg', 'png', 'jpeg', 'JPG', 'JPEG', 'PNG', 'GIF'], 'checkExtensionByMimeType' => false ,'maxFiles' => 4, 'maxSize' => 1024 * 1024 * 1024],
[['extension'], 'string', 'max' => 6],
];
}
Controller code:
if ($mediamodel->load ( Yii::$app->request->post () )) {
$title = UploadedFile::getInstances ( $mediamodel, 'title' );
foreach ($title as $key => $file) {
$file->saveAs(Yii::$app->basePath . '/web/images/hotel/'. $file->baseName . '.' . $file->extension);}
foreach ($title as $key => $file){
echo $mediamodel->title."*********";
$mediamodel->title = $file->baseName . '.' . $file->extension;
echo " \Title: ".$mediamodel->title;
$mediamodel->save ();
}
}
My view code:
use kartik\file\FileInput;
$form = ActiveForm::begin([ 'layout' => 'horizontal', {label}\n{beginWrapper}\n{input}\n{hint}\n{error}\n{endWrapper}",
'fieldConfig' => ['horizontalCssClasses' => ['label' => 'col-md-3','offset' => 'col-md-offset-2','wrapper' => 'col-md-4', 'error' => '','hint' => '',],],'
options' => [ 'class' => 'form-horizontal', 'enctype' => 'multipart/form-data', ], ]);?>
<?php echo $form->field($mediamodel, 'title[]')->widget(FileInput::classname(), ['options'=>['multiple' => true]]);
Html::submitButton($model->isNewRecord ? 'Add' : 'Update');
use
$mediamodel->save (false);
instead of
$mediamodel->save ();
// You should handle errors like this.
if(!$mediamodel->save()){
// handle the errors of model.
var_dump($mediamodel->getErrors());
}

magento 1.9 Edit form is not displaying thumbnail image

I am trying to display thumbnail image on EDIT form in Admin custom module.
I am getting check box to delete image.
I am getting a square box where image supposed to display.
But it's not displaying image.
Please suggest me solution
my save() action in controller is
public function saveAction()
{
if ($data = $this->getRequest()->getPost())
{
if(isset($_FILES['shop_image']['name']) && $_FILES['shop_image']['name'] != '')
{
try {
/* Starting upload */
$uploader = new Varien_File_Uploader('shop_image');
// Any extention would work
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
echo $path = Mage::getBaseDir('media').DS.'ud'.DS;
$uploader->save($path, $_FILES['shop_image']['name'] );
} catch (Exception $e) {
}
// echo $path;exit;
//this way the name is saved in DB
$data['shop_image'] = $path.$_FILES['shop_image']['name'];
}
else if((isset($data['shop_image']['delete']) && $data['shop_image']['delete'] == 1)){
.'ud'.DS.$data['shop_image']['value'];
unlink($data['shop_image']['value']);
//set path to null and save to database
$data['shop_image'] = '';
}
$model = Mage::getModel('shop/shop');
$id = $this->getRequest()->getParam('id');
if ($id) {
$model->load($id);
}
$model->setData($data);
Mage::getSingleton('adminhtml/session')->setFormData($data);
try {
if ($id) {
$model->setId($id);
}
$model->save();
if (!$model->getId()) {
Mage::throwException(Mage::helper('shop')->__('Error saving shop'));
}
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('shop')->__('Shop was successfully saved.'));
Mage::getSingleton('adminhtml/session')->setFormData(false);
// The following line decides if it is a "save" or "save and continue"
if ($this->getRequest()->getParam('back')) {
$this->_redirect('*/*/edit', array('id' => $model->getId()));
} else {
$this->_redirect('*/*/');
}
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
if ($model && $model->getId()) {
$this->_redirect('*/*/edit', array('id' => $model->getId()));
} else {
$this->_redirect('*/*/');
}
}
return;
}
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('shop')->__('No data found to save'));
$this->_redirect('*/*/');
}
my form.php is
<?php
class Sample_Shop_Block_Adminhtml_Shop_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
if (Mage::getSingleton('adminhtml/session')->getExampleData())
{
$data = Mage::getSingleton('adminhtml/session')->getExamplelData();
Mage::getSingleton('adminhtml/session')->getExampleData(null);
}
elseif (Mage::registry('example_data'))
{
$data = Mage::registry('example_data')->getData();
}
else
{
$data = array();
}
$form = new Varien_Data_Form(array(
'id' => 'edit_form',
'action' => $this->getUrl('*/*/save', array('id' => $this->getRequest()->getParam('id'))),
'method' => 'post',
'enctype' => 'multipart/form-data',
));
$form->setUseContainer(true);
$this->setForm($form);
$fieldset = $form->addFieldset('example_form', array(
'legend' =>Mage::helper('shop')->__('Shop Information')
));
$fieldset->addField('shopname', 'text', array(
'label' => Mage::helper('shop')->__('Shop Name'),
'class' => 'required-entry',
'required' => true,
'name' => 'shopname',
'note' => Mage::helper('shop')->__('The name of the shop.'),
));
$fieldset->addField('logo', 'text', array(
'label' => Mage::helper('shop')->__('Logo'),
'class' => 'required-entry',
'required' => true,
'name' => 'logo',
));
$fieldset->addField('productimage', 'text', array(
'label' => Mage::helper('shop')->__('Product Image'),
'class' => 'required-entry',
'required' => true,
'name' => 'productimage',
));
$fieldset->addField('state', 'text', array(
'label' => Mage::helper('shop')->__('State'),
'class' => 'required-entry',
'required' => true,
'name' => 'state',
));
$fieldset->addField('shop_image','image', array(
'label' => Mage::helper('shop')->__('Shop Image'),
'required' => false,
'name' => 'shop_image',
));
$form->setValues($data);
return parent::_prepareForm();
}
}
Find the below easy steps to display the thumbnail image.
Add this below code in your edit ->tab->form file
ex: Package_Campaign_Block_Adminhtml_Campaign_Edit_Tab_Form
$fieldset->addType('image','Package_Campaign_Block_Adminhtml_Campaign_Helper_Image');
Create the below helper class file to display the thumbnail image.
class Package_Campaign_Block_Adminhtml_Campaign_Edit_Tab_Form extends Varien_Data_Form_Element_Abstract{
public function __construct($data) {
parent::__construct($data);
$this->setType('file');
}
public function getElementHtml() {
$html = '';
if ($this->getValue()) {
$media = Mage::getBaseUrl('media').'campaign/';
$html = '<a onclick="imagePreview(\''.$this->getHtmlId().'_image\'); return false;" href="'.$this->getValue().'"><img id="'.$this->getHtmlId().'_image" style="border: 1px solid #d6d6d6;" title="'.$this->getValue().'" src="'.$media.$this->getValue().'" alt="'.$this->getValue().'" width="30"></a> ';
}
$this->setClass('input-file');
$html.= parent::getElementHtml();
return $html;
}
}

Issue on Adding Taxonomy to Custom Post Type Using Function

Using WordPress 3.7.1 and PHP 5.4.12, I am trying to add Custom Post Type and Taxonomy to my Theme, so far the custom post type method works but the Taxonomy is not adding to the Admin Dashboard.
Here is the code I have:
<?php
function add_post_type($name, $args = array()) {
add_action('init', function() use($name, $args) {
$upper = ucwords($name);
$name = strtolower(str_replace(' ','_',$name));
$args = array_merge(
array(
'public'=> true,
'label' => "All $upper" . 's',
'labels' => array('add_new_item' => "Add New $upper"),
'support' => array('title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments')
),
$args
);
register_post_type('$name', $args);
});
}
function add_taxonomy($name, $post_type, $args = array()) {
$name = strtolower($name);
add_action('init', function() use($name, $post_type, $args) {
$args = array_merge(
array(
'label' => ucwords($name),
),
$args
);
register_taxonomy($name, $post_type, $args);
});
}
add_post_type('book', array(
'supports' => array('title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments')
));
add_taxonomy('fun', 'book');
?>
Can you please let me know what part I am doing wrong?
The $name variable is not parsed, put it between double quotes:
register_post_type( "$name", $args );
edit
add_action( 'init', 'so19966809_init' );
function so19966809_init()
{
register_post_type( 'book', array(
'public'=> true,
'label' => 'All Books',
'labels' => array( 'add_new_item' => 'Add New Book' ),
'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ),
'taxonomies' => array( 'fun' )
) );
register_taxonomy( 'fun', 'book', array(
'label' => 'Fun',
) );
}