php foreach multiple array timeout - php

There are two functions, one is init function to get some information from database and then transfer the account info to another function get the data from remote website, then test_function_save_data() get the correct data and check & insert them into the database.
Question is: if use the print_r($post) in test_function_save_data(), the function can work normally. but remove this print_r or replace it with sleep(), all of the data can be checked and inserted into dabase, but the current page is not redirected and blank page will be display.
so, where is wrong? how to solve it?
<?php
function test_function_get_account_init() {
if(test_function_get_sns_account('blog')) {
$b = 0;
foreach (test_function_get_sns_account('blog') as $team_id => $blog_account_name) {
$blog = test_theme_get_blog($team_id, $blog_account_name);
if($blog && is_array($blog['posts'])){
$b += test_function_save_data($blog['posts']);
}
}
echo '<h5successfuly!</h5>';
} else {
echo 'not found.';
}
}
function test_function_save_data($post_data) {
set_time_limit(720);
global $wpdb;
$i = 0;
foreach ($post_data as $post) {
// echo '<div style="display:none;">';
// print_r($post);
// echo '</div>';
if(test_function_check_post_unquine($post['social_origin_id']) && isset($post['social_origin_id'])) {
$social_post_data = array(
'post_title' => $post['post_title'],
'post_content' => $post['post_content'],
'post_status' => 'publish',
'post_author' => get_current_user_id(),
'post_type' => 'social_post'
);
$latest_post_id = wp_insert_post( $social_post_data );
if($post['social_origin_url']) {
add_post_meta($latest_post_id, 'social_origin_url', $post['social_origin_url']);
}
if($post['social_origin_id']) {
add_post_meta($latest_post_id, 'social_origin_id', $post['social_origin_id']);
}
if($post['user']) {
add_post_meta($latest_post_id, 'social_origin_user', $post['user']);
}
if($post['user']['team_account']) {
add_post_meta($latest_post_id, $post['user']['site_name'].'_social_user_id', $post['user']['team_account']);
}
if($post['media']) {
add_post_meta($latest_post_id, 'social_origin_thumbnail', $post['media']['url']);
}
$i++;
}
flush();
}
return $i;
}

This looks like a wordpress code? Have you tested print_r a single $post? In some frameworks, most of the objects are instance of a very complicated class. For ex. In laravel if you try to print_r a single model object it will result in a huge amount of data, so doing it in a loop can cause the timeout. Usually there is a way to get only the object's attributes. Hopefully this helps, maybe this should be in comment but my rep isn't enough for that

Related

Wordpress PHP query is pulling the wrong database entry

first question here!
I have a custom wordpress site in which I have a check out function that includes a discount/coupon code.
I have done the following to test the code:
- I have set-up three coupon codes in my database
- All three coupon codes are in the database with the correct information
When I try to input a coupon, the code is only applying the coupon rules of the last coupon entered. It should instead by pulling the coupon code that matches the user input of $couponcode
I know there is something wrong with the way I'm assigning the $couponID but I can't figure out how to do it correctly.
Note: I am aware of the mis-spelling of: cooupon_title. however it's set-up this way in the database, so that's not the error.
<?php
$couponCode = '';
$couponMessage = '';
$discountAmount = 0;
$couponId = 0;
if(isset($_POST['couponCode']) && !empty($_POST['couponCode'])) {
$couponCode = $_POST['couponCode']; }
if(!empty($couponCode)) {
$args = array('posts_per_page' => 1,'offset' => 0,'category' => '', 'category_name' => '', 'orderby' => 'date','order' => 'DESC','include' => '', 'exclude' => '','meta_key' => '','meta_value' => '','post_type' => 'coupons','post_mime_type' => '','title' => $couponCode,'post_status' => 'publish','suppress_filters' => 'true');
$couponDbData = get_posts($args);
$couponResultData = '';
if(isset($couponDbData[0]) && !empty($couponDbData[0])) {
$couponResultData = $couponDbData[0];
} else {
$couponMessage = 'Invalid coupon code';
}
if(isset($couponResultData->ID) && !empty($couponResultData->ID))
$couponId = $couponResultData->ID;
if(!empty($couponId)) {
$expiry_condition = get_post_meta($couponId,'expiry_condition',true);
$expiry_value = get_post_meta($couponId,'expiry_value',true);
$no_of_use = get_post_meta($couponId,'no_of_use',true);
$appyCoupon = false;
if($expiry_condition=='use') {
if($expiry_value > $no_of_use) {
$appyCoupon = true;
} else {
$couponMessage = 'Coupon has expired.';
}
} else {
$couponExpireTime = strtotime($expiry_value);
$currentTime = time();
if($couponExpireTime > $currentTime) {
$appyCoupon = true;
} else {
$couponMessage = 'Coupon has expired.';
}
}
if($appyCoupon) {
$cooupon_title = get_post_meta($couponId,'cooupon_title',true);
$coupon_type = get_post_meta($couponId,'coupon_type',true);
$coupon_value = get_post_meta($couponId,'coupon_value',true);
if($coupon_type=='$') {
$discountAmount = $coupon_value;
} else {
$discountAmount = ($orderAmount*$coupon_value)/100;
}
$grandTotal -= $discountAmount;
}
}
}
this is my test output:
if($appyCoupon) { ?>
<div class="col-sm-12 col-md-12 makeOrderDetailsrow">
<label class="col-sm-4 col-md-4">Discount <?php echo '( Apply coupon '.$couponCode.' from the following sources '.$couponId.' '.$cooupon_title.' '.$coupon_value.' '.$coupon_type.')'; ?></label>
<span class="col-sm-8 col-md-8">- $<?php echo (number_format($discountAmount,2)); ?></span>
</div>
The output after "from the following sources" shows the code is pulling the last entry in the DB rather than the one that matches the $couponCode. Any advice or suggestions? thank you
According to the codex, the args for get_posts does not include 'title', https://codex.wordpress.org/Template_Tags/get_posts.
Wordpress has a function to query the post by the title, get_page_by_title( $page_title, $output, $post_type );http://codex.wordpress.org/Function_Reference/get_page_by_title
By the way, you don't have to include the whole list of $args in the get_posts query, just those you want to change from the default. For example,
$args = array(
'post_type' => 'coupon',
);
Will override the default of 'post_type' => 'post', without changing 'posts_per_page' => 5.

Wordpress WP_Query not using keyword from url query value?

I'm using a form to change the values in a WP_Query on a custom post type. I have 2 select fields using taxonomy values, and a keyword search. The select fields are working fine, however the keyword doesn't affect the query (although it shows up in the url query string).
The code for the keyword field is:
<input type="text" placeholder="Välj" name="referenser_keyword">
and the code for taking the query values is:
global $wp_query;
if (isset($wp_query->query_vars['referenser_material'])) {
$materialVal = $wp_query->query_vars['referenser_material'];
} else {
$materialVal = '';
}
if (isset($wp_query->query_vars['referenser_segment'])) {
$segmentVal = $wp_query->query_vars['referenser_segment'];
} else {
$segmentVal = '';
}
if (isset($wp_query->query_vars['referenser_keyword'])) {
$keywordVal = $wp_query->query_vars['referenser_keyword'];
} else {
$keywordVal = '';
}
$filteredLoop = new WP_Query(
array(
'post_type' => 'referenser',
'posts_per_page' => 4,
'referenser_material' => $materialVal,
'referenser_segment' => $segmentVal,
's' => $keywordVal,
'exact' => false,
'sentence' => true
)
);
If I change the $keywordVal value in the } else { from '' to a string, it works using the value I've entered, which makes me think it's always not set (and going through as empty in the query).
I hadn't defined the query variables correctly, adding the following to functions.php fixed it.
function referenser_query_vars_filter( $vars ){
$vars[] = "referenser_material";
$vars[] = "referenser_segment";
$vars[] = "referenser_keyword";
return $vars;
}
add_filter( 'query_vars', 'referenser_query_vars_filter' );

Recursive parsing function

I made a function that parses a certain page of a website(a forum thread). It should select users and their posts and then go on to the next page and do the same. While it does that, its return value is always null. I think I made a mistake with the recursion, but can't really figure it out.
Here is the function, I made it return only the userlist, for now.
function getWinners( $thread,$userlist,$postlist ) {
//libxml_use_internal_errors(true);
$html = file_get_html( $thread );
//get users
$users=$html->find( 'li[class="postbitlegacy postbitim postcontainer old"] div[class=username_container] strong span' );
foreach ( $users as $user )
//echo $user . '<br>';
array_push( $userlist, $user );
//get posts
$posts=$html->find( 'li[class="postbitlegacy postbitim postcontainer old"] div[class=postbody] div[class=content]' );
foreach ( $posts as $post )
// echo $post . '<br>';
array_push( $postlist, $post );
//check if there is a next page
if ( $next=$html->find( 'span[class=prev_next] a[rel="next"]', 0 ) ) {
$testa='http://forums.heroesofnewerth.com/'.$next->href;
// echo $testa. '<br>';
$html->clear();
unset( $html );
//recursive calls until the last page of the forum thread
getWinners( $testa,$userlist,$postlist );
//no more thread, return users
}else return $userlist;
}
And the call
$thread='http://forums.heroesofnewerth.com/showthread.php?553261';
$userlist=array();
$postlist=array();
$stuff=getWinners( $thread,$userlist,$postlist);
echo $stuff[0];
Here, stuff is empty.
At the very least you would need to use the value returned from the recursive function:
getWinners( $testa,$userlist,$postlist );
should be:
return getWinners( $testa,$userlist,$postlist );
// or, more likely:
return array_merge($users, getWinners($testa,$userlist,$postlist));
Apart from that I'm not sure if you are returning the right information, probably (you'd need to check...) you need something like:
//cursive calls until the last page of the forum thread
return array_merge($userlist, getWinners($testa,$userlist,$postlist));
}
else {
//no more thread, return users
return $userlist;
}

Alter code to get all posts and show in dropdown list, right kown gets only 5 posts

I know little about php I have tryed to puzzel my way throught this but have not got any where.
I need this dropdown list show all posts right now it shows only 5 posts.
Thank you
Edit: This is the only other bit of code
ob_start();
class externalUrlToPostThumbnail
{
function externalUrlToPostThumbnail(){
try{
add_action('admin_menu', array(&$this,'ext_add_pages'));
}
catch(Exception $e){
echo "Caught Exception".$e->getMessage();
}
}
// action function for above hook
function ext_add_pages(){
add_menu_page(__('Post Featured','mymenu'), __('Featured Image','mymenu'), 'manage_options', 'external-url-post-thumbnail', array ( & $this,'uploadImage'));
}
function uploadImage(){
include_once('external-url-to-post-thumbnail.php');
}
function get_all_post()
{
$options_pages = array();
$options_pages_obj = get_posts('post_type=post');
$options_pages[''] = 'Select a Post:';
foreach ($options_pages_obj as $page) {
$options_pages[$page->ID] = $page->post_title;
}
return $options_pages;
}
}
$newObj = new externalUrlToPostThumbnail();
?>
try replacing the function get_all_post() with the below function.
function get_all_post(){
$options_pages = array();
$args= array(
'posts_per_page' => -1,
'post_type' => 'post',
);
$options_pages_obj = get_posts($args);
$options_pages[''] = 'Select a Post:';
foreach ($options_pages_obj as $page) {
$options_pages[$page->ID] = $page->post_title;
}
return $options_pages;
}

PDO Update 1 column multiple rows with array

I am struggling to workout a good method to update one column of my wcx_options table.
The new data is sent fine to the controller but my function isn't working at all.
I assumed i could loop through each column by option_id updating with the values from the array.
The database:
I update the option_value column with the new information via a jQuery AJAX Call to a controller which then calls a function from the backend class.
So far i have the following code:
if(isset($_POST['selector'])) {
if($_POST['selector'] == 'general') {
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' && isset($_POST['token'])
&& $_POST['token'] === $_SESSION['token']){
$site_name = $_POST['sitename'];
$site_url = $_POST['siteurl'];
$site_logo = $_POST['sitelogo'];
$site_tagline = $_POST['sitetagline'];
$site_description = $_POST['sitedescription'];
$site_admin = $_POST['siteadmin'];
$admin_email = $_POST['adminemail'];
$contact_info = $_POST['contactinfo'];
$site_disclaimer = $_POST['sitedisclaimer'];
$TimeZone = $_POST['TimeZone'];
$options = array($site_name, $site_url, $site_logo, $site_tagline, $site_description, $site_admin, $admin_email,$contact_info, $site_disclaimer, $TimeZone);
// Send the new data as an array to the update function
$backend->updateGeneralSettings($options);
}
else {
$_SESSION['status'] = '<div class="error">There was a Problem Updating the General Settings</div>';
}
}
}
This is what i have so far in terms of a function (It doesnt work):
public function updateGeneralSettings($options) {
$i = 1;
foreach($options as $option_value) {
$where = array('option_id' => $i);
$this->queryIt("UPDATE wcx_options SET option_value='$option_value' WHERE option_id='$where'");
$i++;
}
if($this->execute()) {
$_SESSION['success'] = 'Updated General Settings Successfully';
}
}
With the given DB-layout i'd suggest to organize your data as assiciative array using the db fieldnames, like:
$option = array(
'site_name' => $_POST['sitename'],
'site_url' => $_POST['siteurl'],
// etc.
'timeZone' => $_POST['TimeZone']
);
And than use the keys in your query:
public function updateGeneralSettings($options) {
foreach($options as $key => $value) {
$this->queryIt("UPDATE wcx_options SET option_value='$value' WHERE option_name='$key'");
if($this->execute()) {
$_SESSION['success'] = 'Updated General Settings Successfully';
}
}
}
(However, are you sure, you do not want to have all options together in one row?)
Change your query, you try to use an array as where condition. In the syntax you used that won't work. Just use the counter as where condition instead of define a $where variable. Try this:
public function updateGeneralSettings($options) {
$i = 1;
foreach($options as $option_value) {
$this->queryIt("UPDATE wcx_options SET option_value='$option_value' WHERE option_id='$i'");
$i++;
}
if($this->execute()) {
$_SESSION['success'] = 'Updated General Settings Successfully';
}
}

Categories