Wordpress add_action call function more than 1 time - wordpress

I have function which count page views in Wordrpess, but when I reload page add_action() call function 5 times, I not know why.
<?php
add_action('wp', 'wp125_adview');
function wp125_adview(){
global $wpdb;
$adtable_name = $wpdb->prefix . "wp125_ads";
$url = $_SERVER['REQUEST_URI'];
if(isset($_POST['unique_hidden_field'])) {
$update = "UPDATE ". $adtable_name ." SET views = views+1 WHERE status!=0";
$results = $wpdb->query( $update );
}
}
?>

You have hooked your function call into the 'wp' action hook.
It might be better to use something that should run only once per page, e.g.
add_action('wp_footer', 'wp125_adview');

Related

wordpress hook is not firing

I've read and tried a lot before posting this.
I have a custom sitemap function that I want to trigger on update/create/save post.
I've tried to create new post, update an existing one and just save for the following hooks:
save_post
acf/save_post
pre_post_update
edit_post
the_post
publish_post
Nothing of the above works. I unit tested the function and it does work when hooked on init and admin_init. So I know it's a hook problem. Any advice would be highly appreciated.
All the code:
function pull_active_pages(){
global $wpdb;
$query = $wpdb->get_results(" SELECT * FROM `wp_posts` WHERE (`post_type` LIKE 'page' OR `post_type` LIKE 'post') AND `post_status` LIKE 'publish'; ", OBJECT);
return $query;
}
function makeSitemap(){
$file = 'sitemap.xml'; //that means in the root, provide full path
$query = pull_active_pages();
$output = '<?xml version="1.0" encoding="UTF-8"?>'.PHP_EOL;
$output .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:news="http://www.google.com/schemas/sitemap-news/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd http://www.google.com/schemas/sitemap-news/0.9 http://www.google.com/schemas/sitemap-news/0.9/sitemap-news.xsd">'.PHP_EOL;
foreach((array)$query as $record){
$output .= '<url>'.PHP_EOL;
$url = get_permalink($record->ID);
$output .= '<loc>' . $url . '</loc>'.PHP_EOL;
$last_mod = $record->post_modified_gmt;
$output .= '<lastmod>' . $last_mod .'</lastmod>'.PHP_EOL;
$output .= '<priority>1.00</priority>'.PHP_EOL;
$output .= '</url>'.PHP_EOL;
}
$flags = FILE_APPEND; //redo the whole thing no append for now
$output .='</urlset>';
file_put_contents( $file, $output);
}
add_action('save_post', function(){ makeSitemap();}, 10, 2);
You should change the action like that
add_action('save_post', 'makeSitemap');
and add absolute path to the filename
$file = ABSPATH . '/sitemap.xml'; //that means in the root, provide full path
Check this https://wpengineer.com/2382/wordpress-constants-overview/#ABSPATH
for other absolute paths constants

WP_Query and Woocommerce

I have a function inside (*Wordpress Child Theme) functions.php which returns the attached WooCommerce product categories, using global $wp_query. The get_posts() function will only return the number of products for the first page of products. (*the post_per_page value - in this case 16).
I have tried to temporarily set the post_per_page to -1, by adding the code below right before my function call in archive-product.php template:
$wp_query->set('posts_per_page', 999);
$wp_query->query($wp_query->query_vars);
and then resetting the value after the function call inside archive-product.php template
$wp_query->set('posts_per_page', 16);
$wp_query->query($wp_query->query_vars);
This almost works, but messes up the pre_get_posts function (*which sorts the products), and also seems to cause issues with the listing of the product results if over 500 products?
Please any suggestions would be greatly appreciated. Thanks.
//build dynamic category select menu based on attached categories
function dynamic_category_select() {
global $wp_query;
$my_posts = $wp_query->get_posts();
$my_post_ids = wp_list_pluck($my_posts, 'ID');
$categories = wp_get_object_terms($my_post_ids, 'product_cat');
foreach($categories as $category) {
$options[] = '<option value="' . $category->slug . '">' . $category->name . '</option>';
}
$x = '<select id="category-options" name="category-options">';
$x .= '<option value="">Select Category Options</option>';
foreach($options as $option) {
$x .= $option;
}
$x .= '</select>';
return $x;
}
Try replacing your $my_posts = $wp_query->get_posts(); with the following:
// Get current query vars
$my_query_args = $wp_query->query_vars;
// Disable paging - return all results
$my_query_args['nopaging'] = true;
// Create a new query with the modified query vars
$my_query = new WP_Query($my_query_args);
$my_posts = $my_query->get_posts();

Use postmeta in wordpress shortcode

Trying to get my post meta from posts using shrotcodes and then displaying it on the content.This is the code that's trying to do this:
$string = '';
$custom_content = get_post_custom($post->ID);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post();
$content = get_the_content();
$bonus = $custom_content["bonus"];
$string .= $content . $bonus . '<br>';
endwhile;
}
return $string;
It's not working as the custom content returns empty. Whats wrong? Thanks in advance
I don't think you got the shortcode idea, you should read some info about add_shortcode() also you can use get_post_meta() to retriev the metadata from the database.
Here is an example on how you can achieve this but this will only work with the main loop (as default):
<?php
//you can put this code in functions.php or you can build a plugin for it
function metadata_in_content($attr) {
//this is the function that will be triggerd when the code finds the proper shortcode in the content; $attr is the parameter passed throw the shortcode (leave null for now)
global $wpdb, $wp_query;
//we need global $wpdb to query the database and to get the curent post info
if (is_object($wp_query->post)) {
$post_id = $wp_query->post->post_id;// here we save the post id
$metadata = get_post_meta( $post_id, $key, $single ); // here we get the needed meta, make sure you place the correct $key here, also if you don't want to get an array as response pass $single as "true"
return $metadata; // this finally replaces the shortcode with it's value
}
}
add_shortcode('insert_metadata', 'metadata_in_content');
//the above code hooks the metadata_in_content function to the [insert_metadata] shortcode
?>
Now all it's left to do is to place [insert_metadata] in the post content and things should work.

How can I get the post ID and cat ID in a registered WP action?

In a plugin, via the add_action() routine, I try to run a check. But getting the post ID as below doesn't work, but why? What's the correct way of getting the post ID and a related cat id?
add_action( 'wp', 'check_url', 10, 1 );
function check_url($wp){
if( is_single() ){
$cat_id = wp_get_post_categories( $post->ID );
}
}
Add global to your function first before using $post to make it visible inside your function (this is why we love PHP):
function check_url($wp){
global $post;
...
}

wp_query is empty in admin_init

I'm developing a plugin and one of the issues I am running into is that I cannot get the post id within a function assigned to the admin_init hook.
I tried a few different methods; but, they all seem to use the $wp_query.
Below is a simple version the code I am using. I implemented the code like this just now and ran it by viewing the "post edit" page
add_action('admin_init','do_optional_featured_article');
function do_optional_featured_article()
{
global $wp_query;
echo "<pre>";
print_r($wp_query);
echo "</pre>";
die();
}
$wp_query is a mostly empty array, notably, the post member is empty
-- EDIT --
I got some advice over at wordpress.stackexchange and added in this function:
function get_admin_post()
{
if( isset($_GET['post']) )
{
$post_id = absint($_GET['post']); // Always sanitize
$post = get_post( $post_id ); // Post Object, like in the Theme loop
return $post;
}
elseif( isset($_POST['post_ID']) )
{
$post_id = absint($_POST['post_ID']); // Always sanitize
$post = get_post( $post_id ); // Post Object, like in the Theme loop
return $post;
}
else
{
return false;
}
}
I think this answer will help. It states that the earliest action you can hook into, to get the global $post/$posts variables is the wp action. In the action hook reference on the codex, you can see that the wp action executes a bit after admin_init, which is why you can't retrieve any posts there, I think.
So, that should work:
add_action('wp','do_optional_featured_article');

Resources