WordPress running code from template - wordpress

I have discovered that WordPress is executing code from a template that is in my theme, but when it is not actually on a page using the template.
Although this template will not be used in a live state (since it only runs a loop to create data) I was wondering if anyone else had come across this - and besides shoving everything in functions.php, how to get WP to stop including/running the template when the site load?
I am presuming the reason the code is run, is when WP loads and is looking for templates etc is actual includes(); the template file at some point? which causes the loop to run? if this is the case, does this mean any php in any template file is run?
Here is the code from a the template that is being included (excluding the WP template header) The this code is being run on any page that hasn't got the template set. get_base_question_meta is a function which returns an pre-built array.
$users = get_users( array() );
$base_meta = get_base_question_meta();
$new_meta = array();
foreach ($users as $user ){
if($user->data->ID == 1){
continue;
}
foreach ($base_meta as $question_group_id => $question_groups){
foreach ( $question_groups as $group_id => $sets ){
foreach ($sets as $set_id => $set ){
foreach ($set as $question_id => $question ){
$new_meta[ $group_id ][ $set_id ][ $question_id ] = (string)rand(1, 5);
}
}
}
}
update_user_meta($user->data->ID, 'saved_answers', $new_meta);
}

Related

Wordpress function cannot call submit_button() as it ends with "undefinied function"

i am a real very newbie in coding and in Wordpress. Trying my first test plugin to understand basics. I am able to define plugin, register it, so I can see it in plugins, activate it.
My later goal is to be able to create custom form, save user-specific data to new DB table, and then enable reading/editing it.
I tried to follow the instructions from gmazzap placed here: https://wordpress.stackexchange.com/questions/113936/simple-form-that-saves-to-database
I just am having following error from WP in time of trying to display preview of new screen having a shortcode [userform] in it:
*Fatal error: Uncaught Error: Call to undefined function submit_button() in /data/web/virtuals/131178/virtual/www/subdom/test/system/wp-content/themes/twentytwentythree-child/functions.php:14
*
My functions.php of my theme now looks like this:
<?php
add_action('init', function() {
add_shortcode('userform', 'print_user_form');
});
function print_user_form() {
echo '<form method="POST">';
wp_nonce_field('user_info', 'user_info_nonce', true, true);
?>
All your form inputs (name, email, phone) goes here.
<?php
submit_button('Send Data');
echo '</form>';
}
add_action('template_redirect', function() {
if ( ( is_single() || is_page() ) &&
isset($_POST['user_info_nonce']) &&
wp_verify_nonce($_POST['user_info_nonce'], 'user_info')
) {
// you should do the validation before save data in db.
// I will not write the validation function, is out of scope of this answer
$pass_validation = validate_user_data($_POST);
if ( $pass_validation ) {
$data = array(
'name' => $_POST['name'],
'email' => $_POST['email'],
'phone' => $_POST['phone'],
);
global $wpdb;
// if you have followed my suggestion to name your table using wordpress prefix
$table_name = $wpdb->prefix . 'my_custom_table';
// next line will insert the data
$wpdb->insert($table_name, $data, '%s');
// if you want to retrieve the ID value for the just inserted row use
$rowid = $wpdb->insert_id;
// after we insert we have to redirect user
// I sugest you to cretae another page and title it "Thank You"
// if you do so:
$redirect_page = get_page_by_title('Thank You') ? : get_queried_object();
// previous line if page titled 'Thank You' is not found set the current page
// as the redirection page. Next line get the url of redirect page:
$redirect_url = get_permalink( $redirect_page );
// now redirect
wp_safe_redirect( $redirect_url );
// and stop php
exit();
}
}
});
Note: I have not got to DB exercise, point of my question is submit_button.
As indicated in the error, the code on line 1 points to non identified function:
submit_button('Send Data');
I understood from other discussions submit_button should be core function of WP, so I should be able to call it "directly", without the need of a definition.
I tried following:
originally had very similar code within the plugin, moved to functions.php
reinstalled core of WordPress version 6.1.1
tried several different Themes (as it looked this worked for other users, I tried "classic" and "twentytwentythree" )
And still no little step further, still having same issue with error described above. What I am doing wrong?
If someone would confirm this is WP core installation issue, I am ready to reinstall WP from scratch, just trying to save some time, if there might be other cause.
Thank you for any suggestions.

Use ACF load_value hook to pre-populate the Upload File field

I'm trying to pre-populate the File upload field with files already submitted previously, using ACF PRO and ACF Frontend Form.
So far, I am able to retrieve a list of files that was previously uploaded but can't seem to figure out a way to set it in the file upload frontend.
The File upload field lives inside a Repeater group.
In the functions.php:
I added a load_value with key set to the repeater group:
add_filter('acf/load_value/key=field_5e80ed8f4516b', 'my_acf_set_file_list', 10, 3);
Then in the function I attempted to set the $value to be an array of file urls.
'field_5e80edf14516c' is the key for the File field.
function my_acf_set_file_list( $value, $post_id, $field ){
$order_id = $_GET['order'];
$value = array();
// get existing files
$existing_files = get_post_meta( $order_id, 'file', true);
if ( !empty( $existing_files ) ) {
$i = 0;
foreach ( $existing_files as $file ) {
$value[$i]['field_5e80edf14516c'] = $file;
// also tried
// $value[$i]['field_5e80edf14516c'] = $file['file'];
}
}
return $value;
}
The problem is in the frontend form, there seems to be no change at all. No file was pre-populated.
I'm pretty sure I didn't get the array structure correct, but I've searched all over and cannot find any related information.
The post data for when I upload existing files seem to indicate the attachment ID is used. But I'm not sure what is the row-0 and other id 5ebf042bba99f?
acf[field_5e80ed8f4516b]:
acf[field_5e80ed8f4516b][row-0][field_5e80edf14516c]: 381
acf[field_5e80ed8f4516b][5ebf042bba99f][field_5e80edf14516c]: 381
acf[field_5e80ed8f4516b][5ebf042cba9a0][field_5e80edf14516c]: 401
Thanks in advance!

automatic wordpress core and plugin version monitoring to json file

because of a lot of Wordpress Sites I have to maintain, I created a little function which generates a json file with the latest Core & Plugin Update informations. My monitor page than gets this json files via curl and displays them in a list.
The problem is, the data in the json file seems only to be actualized, after a backend login. I tried to use the init action to have it working without a backend login, but it doesn't.
Has someone an idea, how to fix it? I would like to get an actual state every 72 hours. Here is my function from functions.php:
function wpCheckUpdateState() {
$upload_dir = wp_upload_dir();
$file = $upload_dir['basedir'] . '/version.json';
// check only every 72 hours (259200sec)
if( is_writeable($upload_dir['basedir']) && ( !is_readable($file) || filemtime($file) < time() - 259200) ) {
if( function_exists('file_put_contents') ) {
$data['rebuild'] = false;
if( get_site_transient('update_plugins') == false) {
wp_update_plugins();
$data['rebuild'] = true;
}
$plugins = get_site_transient( 'update_plugins' );
$data['wp-version'] = get_bloginfo('version');
$data['updated'] = date('d.m.y H:i', $plugins->last_checked);
$data['plugins']['update'] = count($plugins->response);
$data['plugins']['no_update'] = count($plugins->no_update);
$json_data = json_encode($data);
file_put_contents($file, $json_data);
}
}
}
add_action( 'init', 'wpCheckUpdateState' );

drupal 7 modify taxonomy page with hook_alter_menu

i want to change or modify all taxonomy pages i write this piece of code in template.php in my bartik theme but some weird things happens.
the $term argument in second function "bartik_term_page" is null.
what is missing?
and it sometimes an error like this
it gives an error.
Warning: Parameter 1 to bartik_term_page() expected to be a reference, value given in menu_execute_active_handler() (line path\includes\menu.inc).
function bartik_menu_alter(&$menu) {
$menu['taxonomy/term/%']['page callback'] = 'bartik_term_page';
$menu['taxonomy/term/%']['access arguments'] = array('access content');
}
function bartik_term_page(&$term){
$voc = taxonomy_vocabulary_load($term->vid);
var_dump( $term ); die();
// here you generate the actual content of the page
// could be done e.g. with an entityfieldquery as follows
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
->fieldCondition('field_category', 'tid', $term->tid);
$result = $query->execute();
if (!empty($result['node'])) {
$build['content']['nodes'] = node_view_multiple(node_load_multiple(array_keys($result['node'])), 'teaser'); // output the node teasers. you can control the markup of the 'teaser' view mode with a template in the theme folder
} else {
$build['content']['status']['#markup'] = t('No results found for term ID !tid.', array('!tid' => $term->tid));
}
return $build;
}
You're actually introducing a new router item there instead of overriding the existing one.
The path for the taxonomy page is taxonomy/term/%taxonomy_term, so...
function bartik_menu_alter(&$menu) {
$menu['taxonomy/term/%taxonomy_term']['page callback'] = 'bartik_term_page';
$menu['taxonomy/term/%taxonomy_term']['access arguments'] = array('access content');
}
Clear caches and you should be good to go.
Add the following line after the 'page callback' line in your bartik_menu_alter() function:
$menu['taxonomy/term/%']['page arguments'] = array(3);
This tells Drupal where to find the parameter in your URL (it's the third component).

Wordpress creating plugin for most viewed posts problem?

I just want to create plugin that will when visitor(user,visitor,...) visit some post,remember what post,and to increment counter of that post,I wrote this code,but sometimes,counter is incremented,even post isn't viewed,or post with other Id is added to a table.Can someone help me with this,please.I know that there are plugins for this that I'm trying to do,but still want to write this plugin.
function IncrementPostCount($the_content) {
global $post;
global $wpdb;
if(($post->post_status == 'publish') && (int)$post->ID) {
if(is_single()) { // just for single post - not for page
$postID = (int)$post->ID;
$postTitle = urlencode($post->post_title);
$postLink = urlencode(get_permalink($post->ID));
$oneRow = $wpdb->get_row("SELECT * FROM wp_postovi WHERE postAjDi='$postID'");
if(empty ($oneRow)) {
$postCounter = 1;
$data_array = array(
'readnTimes' => $postCounter,
'linkPost'=>$postLink,
'TitlePost'=>$postTitle,
'postAjDi'=>$postID);
$wpdb->insert('wp_najcitaniji_postovi', $data_array);
}
else {
$postCounter = intval($oneRow->readnTimes) + 1;
$data_array = array('readnTimes' => $postCounter);
$where_array = array('postAjDi'=>intval($oneRow->postAjDi));
$wpdb->update('wp_postovi',$data_array,$where_array);
}
return $the_content;
}
return $the_content;
}
}
add_filter('the_content','IncrementPostCount');
Sorry on my bad english,tnx in advance.
Here's how to do that with the postmeta table.
function IncrementPostCount(){
if(is_single()){
global $wp_query;
$count = get_post_meta( $wp_query->post->ID, 'readnTimes', true );
$count = empty($count) ? 1 : $count + 1;
add_post_meta($wp_query->post->ID, 'readnTimes', $count, true) or update_post_meta($wp_query->post->ID, 'readnTimes', $count);
}
}
add_action( 'template_redirect', 'IncrementPostCount' );
Also, it's better to hook it in earlier. That way, the count is only incremented once per page load (the_content can be fired multiple times per page, even on a single page. template_redirect only fires once per request). Also, if you store the data at template_redirect, you can use the updated view count in the template, giving your visitors an even more accurate view count.
And you don't need to worry about database tables, custom SQL, or any of that.

Resources