I have the following code based on this great template for making custom WordPress widgets:
<?php class DRCC_Feat extends WP_Widget {
function dr_post_select_list() {
$drcc_posts_args = array(
'post_type' => array( 'post', 'page', 'tribe_events' ),
'numberposts' => -1,
'orderby' => 'title',
'order' => 'ASC'
);
$drcc_posts = get_posts( $drcc_posts_args );
$dr_posts_array = array();
foreach( $drcc_posts as $post ) {
$dr_posts_array[$post->ID] = $post->post_title;
}
return $dr_posts_array;
}
protected $widget = array(
'description' => 'Custom widget for my client.',
'do_wrapper' => true,
'view' => false,
'fields' => array(
array(
'name' => 'Post to Feature',
'desc' => 'Enter the IDs of any posts, pages, etc. If more than one, separate with commas.',
'id' => 'dr_feat_ids',
'type' => 'select',
'options' => dr_post_select_list(),
'std' => ''
)
)
);
// some more stuff here, but the error is above and the code works when I make 'options' somethings hard-coded.
} ?>
I am trying to call dr_post_select_list() in the protected $widget array to dynamically generate a list of posts, but I get the error Parse error: syntax error, unexpected '(', expecting ')' in reference to the line with the dr_post_select_list() function in it. It's as if it doesn't recognize that it's a function.
I've tried the function elsewhere and it works fine. I've tried making the array public and that doesn't change anything. I've tried saving the function output in an array and putting the variable in the array
I get the sense that I'm doing something fundamentally wrong.
tl;dr - method called in array in a class doesn't run (or seem to be recognized as a method).
You're missing a closing } for your function.
Replace your code with the following:
<?php
class DRCC_Feat extends WP_Widget {
protected $widget = array(
'description' => 'Custom widget for my client.',
'do_wrapper' => true,
'view' => false,
'fields' => array(
array(
'name' => 'Post to Feature',
'desc' => 'Enter the IDs of any posts, pages, etc. If more than one, separate with commas.',
'id' => 'dr_feat_ids',
'type' => 'select',
'options' => 'dr_post_select_list',
'std' => ''
)
)
);
function dr_post_select_list() {
$drcc_posts_args = array(
'post_type' => array( 'post', 'page', 'tribe_events' ),
'numberposts' => -1,
'orderby' => 'title',
'order' => 'ASC'
);
$drcc_posts = get_posts( $drcc_posts_args );
$dr_posts_array = array();
foreach( $drcc_posts as $post ) {
$dr_posts_array[$post->ID] = $post->post_title;
}
return $dr_posts_array;
}
}
Edited: Moved all code inside class, corrected error. Have a look at this post as well in regards to storing functions in an array. Slightly different than say JS.
Can you store a function in a PHP array?
Related
I've tried a bunch of different functions and approaches but so far I haven't been able to get it working.
The goal is to add an Advanced Custom Field group to the backend of Wordpress with some PHP-code. In the best scenario we add the PHP-code to a method of a class.
public function create_group( $group_name ) {
if ( $this->does_group_already_exists( $group_name ) ) {
return false;
}
acf_add_local_field_group( array(
'key' => 'group_1',
'title' => 'My Group',
'fields' => array(
array(
'key' => 'field_1',
'label' => 'Sub Title',
'name' => 'sub_title',
'type' => 'text',
)
),
'location' => array(
array(
array(
'param' => 'post_type',
'operator' => '==',
'value' => 'post',
),
),
),
) );
return true;
}
Nothing gets added with the code above. I also tried adding it to functions.php and it with a add_action() function like so:
add_action( 'acf/init', array( $this, 'create_group' ) );
But again, no results.
Hope some one can share a working solution.
Today I finally discovered a solution for adding a ACF group to the backend dynamically with PHP-code.
It can be done by adding a new post directly with the acf-field-group post type. Here is my implementation for those awesome people from the future that are interested:
public function create_form( $form_name ) {
$new_post = array(
'post_title' => $form_name,
'post_excerpt' => sanitize_title( $form_name ),
'post_name' => 'group_' . uniqid(),
'post_date' => date( 'Y-m-d H:i:s' ),
'comment_status' => 'closed',
'post_status' => 'publish',
'post_type' => 'acf-field-group',
);
$post_id = wp_insert_post( $new_post );
return $post_id;
}
Where $form_name is the name of the ACF group. It works. And there was no need for using a specific hook. I could just call this method directly.
Actually you can create such code over ACF in the WP-Backend itself (not sure if this only works in ACF Pro). Under Admin -> Custom Fields -> Tools -> Export -> Create PHP. The generated code is a great starting point for a programmatic ACF integration.
It should look something like this:
acf_add_local_field_group(array(
'key' => 'group_5d146d18eeb92',
'title' => 'My Group Title',
'fields' => array(
array(
'key' => 'field_5d146d1f27577',
'label' => 'My Field Title',
'name' => 'my_field_name',
'type' => 'true_false',
'instructions' => '',
'required' => 0,
'conditional_logic' => 0,
'wrapper' => array(
'width' => '',
'class' => '',
'id' => '',
),
'message' => '',
'default_value' => 0,
'ui' => 1,
'ui_on_text' => '',
'ui_off_text' => '',
),
),
'location' => array(
array(
array(
'param' => 'post_type',
'operator' => '==',
'value' => 'my_custom_post_type',
),
),
),
'menu_order' => 0,
'position' => 'side',
'style' => 'default',
'label_placement' => 'top',
'instruction_placement' => 'label',
'hide_on_screen' => '',
'active' => true,
'description' => '',
));
Check out the ACF page for registering fields via PHP.
Action acf/init is available for pro version only, maybe that was the reason it did not work at the first place..
For basic version you have to use acf/register_fields to register your custom fields.
I've never worked with php or wordpress but is trying to use an custom post api from wordpress.
I've found this link: https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-rest-api-support-for-custom-content-types/
where they say that I can just add similar code like below and it should work.
add_action( 'init', 'my_book_cpt' );
function my_book_cpt() {
$args = array(
'public' => true,
'show_in_rest' => true,
'label' => 'Books'
);
register_post_type( 'book', $args );
}
But since I'm full newby here I don't know which file to put this in? Does anyone know? Thanks!
Johan, you will need to register a custom WP REST API path in your functions.php, something like this:
add_action('rest_api_init', 'yourPathName');
function yourPathName(){
register_rest_route('nameItHere/version#', 'routNameHere', array(
'methods' => WP_REST_SERVER::READABLE,
'callback' => 'nameACallbackFunction',
));
}
function nameACallbackFunction($data) {
$variablename = new WP_Query(array(
'post_type' => 'name_of_your_post_type',
'posts_per_page' => 5,
's' => $data['term'],
'orderby' => 'title',
'order' => 'asc'
));
$anotherVariable = array();
while ($variableName->have_posts()) {
$variableName->the_post();
array_push($anotherVariable, array(
'id' => get_the_ID(),
'title' => get_the_title(),
'content' => get_the_content()
));
}
return $anotherVariable;
}
Then you can reference your new endpoint and the data within it in your JS AJAX call using XMLHttpRequest()
I can't use self in a static method , it gives me this error message :
Fatal error: Using $this when not in object context in C:\xampp\htdocs\wordpress\wp-content\plugins\dw-usercp\usercp.php on line 136
here is the source code :
class dw_usercp
{
public static function plugin_activated() {
self::create_plugin_pages();
}
public function create_plugin_pages() {
$pages = array(
'signin' => array(
'title' => __( 'Sign In', 'dw-usercp' ),
'content' => '[dwusercp-sigin-form]',
'option_id' => 'login_page'
),
'user-account' => array(
'title' => __( 'Your Account', 'dw-usercp' ),
'content' => '[dwusercp-info]',
'option_id' => 'user_account_page'
),
'edit-user-info' => array(
'title' => __( 'Edit User Info', 'dw-usercp' ),
'content' => '[dwusercp-edit-info]',
'option_id' => 'user_editinfo_page'
),
'profile' => array(
'title' => __( 'User profile', 'dw-usercp' ),
'content' => '[dwusercp-profile]',
'option_id' => 'profile_page'
),
'signup' => array(
'title' => __( 'Sign Up', 'dw-usercp' ),
'content' => '[dwusercp-signup-form]',
'option_id' => 'register_page'
),
'user-lost-password' => array(
'title' => __( 'Forgot Your Password?', 'dw-usercp' ),
'content' => '[dwusercp-password-lost-form]',
'option_id' => 'lost_password_page'
),
'user-password-reset' => array(
'title' => __( 'Pick a New Password', 'dw-usercp' ),
'content' => '[dwusercp-password-reset-form]',
'option_id' => 'password_reset_page'
)
);
foreach( $pages as $slug => $page ) {
$query = new WP_Query( 'pagename=' . $slug );
if ( ! $query->have_posts() ) {
// Add the page using the data from the array above
$post_id = wp_insert_post(
array(
'post_content' => $page['content'],
'post_name' => $slug,
'post_title' => $page['title'],
'post_status' => 'publish',
'post_type' => 'page',
'ping_status' => 'closed',
'comment_status' => 'closed',
)
);
$this->update_plugin_option( $page['option_id'], $post_id ); // this is the line 136 that the error message says
}
}
}
/**
* Update plugin option
*
* #param string $field option id
* #param mixed $value option new value
* #return bool
*/
public function update_plugin_option( $field, $value ) {
$options = get_option("dw_usercp_options");
$options[$field] = $value;
update_option( "dw_usercp_options", $options );
}
}
$dw_usercp = new dw_usercp();
register_activation_hook( __FILE__, array( 'dw_usercp', 'plugin_activated' ) );
how do i call the create_plugin_pages() correctly then?
the plugin_activated() has to be static as Wordpress says
Inside a static function, you're not in an instance of the class. You could:
instantiate an instance of the class and call the function
Pass an instatiated object into the static funtion
Make the create_plugin_pagesfunction static and call it with static.
Convert plugin_activated to not be static (MY VOTE)
The static option won't work though since you call $this inside create_plugin_pages. So you'll need to go the instatiation route.
Non-static
public function plugin_activated() {
$this->create_plugin_pages();
}
Here's the passing in an object version
public static function plugin_activated(dw_usercp $a_dw_usercp) {
$a_dw_usercp->create_plugin_pages();
}
Its because you are using "$this" variable when you're in static context (did you read the error message?)
When in static context, use for methods:
self::method(args);
or
self::$attr for variables (attributes)
$this->update_plugin_option( $page['option_id'], $post_id );
is not self, as referenced in your title. You should be using:
self::update_plugin_option( $page['option_id'], $post_id );
Thank you for taking the time to read this, I'll explain best I can. Any help is appreciated.
I have a checkbox group available for me to use for each of my Wordpress posts. It allows me to tick/check which people are featured in the current post. I achieved this by adding this code to my functions.php file:
function add_custom_meta_box() {
add_meta_box(
'custom_meta_box',
'Featured People',
'show_custom_meta_box',
'post',
'side',
'core'
);}
add_action('add_meta_boxes', 'add_custom_meta_box');
// Field Array
$prefix = 'custom_';
$custom_meta_fields = array(
array (
'label' => '',
'desc' => '',
'id' => $prefix.'checkbox_group',
'type' => 'checkbox_group',
'options' => array (
'1' => array (
'label' => 'Person One',
'value' => 'personone'
),
'2' => array (
'label' => 'Person Two',
'value' => 'persontwo'
),
'3' => array (
'label' => 'Person Three',
'value' => 'personthree'
),
'4' => array (
'label' => 'Person Four',
'value' => 'personfour'
// Add More People Here
),
)
)
);
This works all fine, however, I'm sure you'll agree that it would be very tedious to keep adding people each time there's a new person.
So, in an attempt to make this checkbox group more dynamic, I created a new custom post type that allows me to add the information for each person the same way you would add the content for a normal post in wp-admin. The only problem is I can't figure out how to loop through this custom post type in functions.php.
This is what I want to do:
array (
'label' => '',
'desc' => '',
'id' => $prefix.'checkbox_group',
'type' => 'checkbox_group',
'options' => array (
$args = array(
'post_type' => 'featured-people', //LOOP THROUGH THIS POST TYPE
'posts_per_page' => -1 );
$query = new WP_Query( $args );
while ($query->have_posts()) : $query->the_post();
'the_title();' => array ( //FOR EACH, DO THIS
'label' => 'the_title();',
'value' => 'the_value();'
),
endwhile
I'm hoping to make this post type populate the checkbox group, and each time a new person is added, the checkbox group will update to include them as an option.
(I then have to figure out how to display the information on single.php, but one thing at a time).
Any help would be greatly appriciated. Thank you!
You were pretty darn close. The easiest way is to store the options in a variable, do the loop, then do the rest. This should get you started:
///store options
$options = array();
$args = array(
'post_type' => 'featured-people',
'posts_per_page' => -1
);
$query = new WP_Query( $args );
//loop query
while ($query->have_posts()) : $query->the_post();
//get_the_title returns the post title
//bracket notation stores it as the array key
$options[get_the_title()] => array (
'label' => get_the_title(),
//get post meta's last parameter decides if it is a string
//might need to play with this part a bit
'value' => get_post_meta(get_the_ID(), 'custom_meta_box' true)
);
endwhile;
$custom_meta_fields = array(
array (
'label' => '',
'desc' => '',
'id' => $prefix.'checkbox_group',
'type' => 'checkbox_group',
'options' => $options //reference our previous array
)
);
EDIT
You could technically create a self-invoking function with call_user_func if you want the wanted to do the logic 'inline', although it's a bit of an odd pattern:
$custom_meta_fields = array(
array (
'label' => '',
'desc' => '',
'id' => $prefix.'checkbox_group',
'type' => 'checkbox_group',
'options' => call_user_func(function(){
///store options
$options = array();
$args = array(
'post_type' => 'featured-people',
'posts_per_page' => -1
);
$query = new WP_Query( $args );
//loop query
while ($query->have_posts()) : $query->the_post();
$options[get_the_title()] => array (
'label' => get_the_title(),
'value' => get_post_meta(get_the_ID(), 'custom_meta_box' true)
);
endwhile;
return $options;
})
)
);
am working on a wordpress admin panel using startbox admin panel, where I want to list all categories with slug and name inside an array but it seems impossible for me to make it work, here is my code
$args = array(
'type' => 'post',
'child_of' => 0,
'parent' => '',
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => 1,
'hierarchical' => 1,
'exclude' => '',
'include' => '',
'number' => '',
'taxonomy' => 'category',
'pad_counts' => false
);
$args = array(
'orderby' => 'name',
'order' => 'ASC'
);
$categories = get_categories($args);
// This much above code is given by wordpress to get all categories, mine starts below
class sb_slider_settings extends sb_settings {
function sb_slider_settings() {
$this->slug = 'sb_slider_settings';
$this->options = array(
'on_off_news' => array(
'type' => 'select',
'default' => 'true',
'label' => __( 'Enable breaking news', 'startbox' ),
'options' => array(
'false' => __( 'No', 'startbox' ),
'true' => __( 'Yes', 'startbox' ),
)
),
'ticker_text' => array(
'type' => 'select',
'default' => 'true',
'class' => 'ticker_text',
'label' => __( 'Extract posts from', 'startbox' ),
'options' => array(
foreach($categories as $category) {
$category->slug => __( $category->name , 'startbox' ) ;
}
)
)
);
parent::__construct();
}
}
Error it shows,
Parse error: syntax error, unexpected 'foreach' (T_FOREACH), expecting ')'
However you can user array_map to call same function on each element of an array :
http://us1.php.net/manual/fr/function.array-map.php
In your case,
'options' => array_map('callback', $categories),
and your callback
function callback($category) {
return __( $category->name , 'startbox' );
);
You can't execute code inside an array. An array is intended to have fixed values in it.
http://es1.php.net/manual/en/language.types.array.php
To do what you wanna do you must create a function and call that function inside your array.