I have added this cronjob in my WordPress custom plugin but when I run the function manually it is working but through cronjob, it is not working. Here is my code! All the plugin files are loaded correctly not showing any error.
Can anybody help me to sort this out! I have tried a lot but still, it is not working.
<?php
if (!wp_next_scheduled('generateusedcarsfeed'))
{
wp_schedule_event(time() , '5mins', 'generateusedcarsfeed');
}
add_action('generateusedcarsfeed', 'generate_used_car_feed');
if (!wp_next_scheduled('generateusedcarsfeed'))
{
wp_schedule_event(time() , '5mins', 'generateusedcarsfeed');
}
add_action('generateusedcarsfeed', 'generate_used_car_feed');
// Getting all used cars with all data
function generate_used_car_feed(){
try{
// for opening the csv file
$file = fopen('all-cars-feed.csv', 'r');
fwrite($file, '');
$loop = new WP_Query($args);
chmod('all-cars-feed.csv', 0777);
// for creating array from csv file
$file="all-cars-feed.csv";
$csv= file_get_contents($file);
$array = array_map("str_getcsv", explode("\n", $csv));
$json_csv_arr = json_encode($array);
$my_array_csv = json_decode($json_csv_arr, true);
// for getting used car list from databse, only take publish used car
global $wpdb;
$query = "SELECT wp_postmeta.post_id, wp_postmeta.meta_value FROM wp_postmeta
INNER JOIN wp_posts ON wp_posts.id = wp_postmeta.post_id WHERE meta_key = 'car_registration_number'
AND post_status = 'publish'";
$result = $wpdb->get_results($query);
$json_reg_num = json_encode($result);
$my_array = json_decode($json_reg_num, true);
print_r($my_array);
foreach ($my_array as $value) {
$car_reg_array = $value['meta_value'];
$Post_id= $value['post_id'];
$isTrue=true;
$ch = fopen("all-cars-feed.csv", "r");
while($row = fgetcsv($ch)) {
if (in_array($car_reg_array, $row)) {
echo 'found</hr>';
$isTrue=false;
}
}
if($isTrue)
{
$wpdb->query(
'UPDATE '.$wpdb->prefix.'posts SET post_status = "trash"
WHERE ID = "'.$Post_id.'"');
}
}
//fclose($file);
}
catch(\Exception $e)
{
$txt = 'Message: ' . $e->getMessage();
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
fwrite($fileLoger, $txt);
fclose($fileLoger);
}
}
I wonder if this 5mins interval really exists in your setup. Try adding this code to make sure this actually exists (if it does already, it won't break stuff):
function add_custom_cron_schedules($schedules){
if (!isset($schedules["5mins"])) {
$schedules["5min"] = array(
'interval' => 5*60,
'display' => __('Every 5 minutes'));
}
return $schedules;
}
add_filter('cron_schedules','add_custom_cron_schedules');
If you want to retrieve currently available schedules, you can also use wp_get_schedules() and check out if a certain key (like '5mins') exists.
Related
I have created a plugin to insert and fetch records. When I save record, record is getting saved from localhost but when I try it on online server it is not getting saved. Here is what I am trying to do.
function data_custom_ajax(){
global $wpdb;
$tbl = "tripplan";
$table_name=$wpdb->prefix . $tbl;
$custom_val = $_POST['text'];
$totaltime = $_COOKIE['totalduration'];
$totaldistance = $_COOKIE['totaldistance'];
$origin_address = $custom_val['originaddress'];
$end_address = $custom_val['destinationaddress'];
$waypoints = $custom_val['waypts'];
$wpdb->insert($table_name,
array(
'startpoint' => $origin_address,
'endpoint' => $end_address,
'waypoints' => json_encode($waypoints),
'totaldistance' => $totaldistance,
'totalduration' => $totaltime
),
array('%s','%s','%s','%f','%f')
);
echo "data has been saved";
}
function data_custom_ajax(){
global $wpdb;
$tbl = "tripplan";
$table_name=$wpdb->prefix . $tbl;
$custom_val = $_POST['text'];
$totaltime = $_COOKIE['totalduration'];
$totaldistance = $_COOKIE['totaldistance'];
$origin_address = $custom_val['originaddress'];
$end_address = $custom_val['destinationaddress'];
$waypoints = $custom_val['waypts'];
$data = array(
'startpoint' => $origin_address,
'endpoint' => $end_address,
'waypoints' => json_encode($waypoints),
'totaldistance' => $totaldistance,
'totalduration' => $totaltime
)
$lastInsertedId = $wpdb->insert($table_name,$data);
if($lastInsertedId != '')
{
echo "data has been saved";
}else{
$wpdb->print_error();
}
die();
}
After lot of reading and debugging I got to know the problem. My cookie was not getting saved correctly. Even though it was working on localhost, it was not working on website. After reading this [PHP cannot read javascript cookies and then after I modified my cookie while saving.
I was setting cookie like this and it was not working-
document.cookie="cookiename="+value
after setting this way it worked -
document.cookie = 'cookiename='+value+'; path=/'
I have an Object that extends Page ("Thing") which has a many_many relationship with a DataObject ("Tag").
class Thing extends Page
{
static $many_many = array(
'Tags' => 'Tag'
);
}
class Tag extends DataObject
{
static $belongs_many_many = array(
'Things' => 'Thing'
);
}
I have an array of Tag IDs and I want to get a list of Things that have all of these tags attached.
The following should be possible...
$tag_ids = array(1,2,3,4);
$things = Thing::get();
$things->filter('Tags.ID', array($tag_ids));
...but this just returns an unfiltered list. Apparently this hasn't been implemented for relationships yet. So how can I do it?
I think if you are using older versions for SilverStripe 3, you need to use the ExactMatchMulti SearchFilter.
$tag_ids = array(1,2,3,4);
$things = Thing::get();
$things->filter('Tags.ID:ExactMatchMulti', $tag_ids);
I don't see an easy solution do do this directly with the ORM. But you should be able to solve this with some loops and filtering.
$tag_ids = array(1,2,3,4);
$things = Thing::get();
$results = new ArrayList();
$tags_count = count($tag_ids);
$matches = 0;
foreach ($things as $thing)
{
foreach ($thing->Tags() as $tags)
{
$matches = 0;
foreach ($tags as $tag)
{
if ( in_array($tag->ID, $tag_ids) )
{
$matches++;
}
}
if ( $matches === $tags_count )
{
$results->push($thing);
}
}
}
Although not tested, this should leave you with $things that contain those with all tags and more. (Assuming a thing can only be tagged once with the same tag).
For performance reasons you would probably be better off relying as much as possible on a sql query.
$tag_ids = array(1,2,3);
$objects = new ArrayList();
if (count($tag_ids)) {
$sql = "SELECT \"SiteTree\".*, \"Page\".*, \"Thing\".*,count(\"ThingID\") AS ThingIDCount FROM \"SiteTree\" ";
$sql.= "LEFT JOIN \"Page\" ON \"Page\".\"ID\" = \"SiteTree\".\"ID\" ";
$sql.= "LEFT JOIN \"Thing\" ON \"Thing\".\"ID\" = \"SiteTree\".\"ID\" ";
$sql.= "LEFT JOIN \"Thing_Tags\" ON \"Thing_Tags\".\"ThingID\" = \"SiteTree\".\"ID\" ";
$sql.= "LEFT JOIN \"Tag\" ON \"Thing_Tags\".\"TagID\" = \"Tag\".\"ID\" ";
$sql.= "WHERE \"TagID\" IN (" . implode(',', $tag_ids) . ") GROUP BY \"ThingID\" HAVING ThingIDCount >= " . count($tag_ids);
// Get records
$records = DB::query($sql);
foreach($records as $record) {
$objects->push(new Thing($record));
}
}
// Display the Things for demo purposes
foreach($objects as $thing){
Debug::Dump($thing);
}
NB I have added a left join to a Thing table, as I imagine you have some db fields on it, but drop the line (and the \"Thing\".* on the SELECT statement) if that's not the case
You can try to do the following:
Tag::get()->byIds($tag_ids)->relation('Things')
which will return a ManyManyList that you can iterate over, ie
foreach(Tag::get()->byIds($tag_ids)->relation('Things') as $thing){
Debug::Dump($thing); // A 'Thing' object
}
Hope this helps
I have a script which successfully creates new nodes. But I'm having trouble setting the taxonomy before saving.
I believe in Drupal 6 I would use this method.
$cat1_tid = taxonomy_get_term_by_name($data[$i]['cat1']);
$cat2_tid = taxonomy_get_term_by_name($data[$i]['cat2']);
$cat3_tid = taxonomy_get_term_by_name($data[$i]['cat3']);
$node->taxonomy = array($cat1_tid, $cat2_tid, $cat3_tid);
I think in Drupal 7 I would do this (my field name is Catalog)
$node->taxonomy_catalog['und'][0] = array($term1Obj, $term2Obj);
taxonomy_get_term_by_name doesn't seem to return the correct object to insert into the node object.
If anyone can shed some light, appreciated.
Thanks
EDIT
Solution:
// Taxonomy
$categories = array($data[$i]['cat1'], $data[$i]['cat2'], $data[$i]['cat3']);
foreach ($categories as $key => $category) {
if ($term = taxonomy_get_term_by_name($category)) {
$terms_array = array_keys($term);
$node->taxonomy_catalog[LANGUAGE_NONE][$key]['tid'] = $terms_array['0'];
}
}
Below is some quick-and-dirty code I used recently to import "command" nodes into a site. Mid-way down, the foreach loop takes care of creating and assigning terms, as needed.
$command = new stdClass;
$command->language = LANGUAGE_NONE;
$command->uid = 1;
$command->type = 'drubnub';
$command->title = $line['0'];
$command->body[LANGUAGE_NONE]['0']['value'] = $line['1'];
$command->url[LANGUAGE_NONE]['0']['value'] = trim($line['2']);
$command->uses[LANGUAGE_NONE]['0']['value'] = $line['3'];
$tags = explode(',', $line['4']);
foreach ($tags as $key => $tag) {
if ($term = taxonomy_get_term_by_name($tag)) {
$terms_array = array_keys($term);
$command->field_tags[LANGUAGE_NONE][$key]['tid'] = $terms_array['0'];
} else {
$term = new STDClass();
$term->name = $tag;
$term->vid = 1;
if (!empty($term->name)) {
$test = taxonomy_term_save($term);
$term = taxonomy_get_term_by_name($tag);
foreach($term as $term_id){
$command->product_tags[LANGUAGE_NONE][$key]['tid'] = $term_id->tid;
}
$command->field_tags[LANGUAGE_NONE][$key]['tid'] = $tid;
}
}
}
node_save($command);
Here you are, this code successfully add a new term to the node before the node is created.
$my_term_name = 'micky';
$term_array = taxonomy_get_term_by_name($my_term_name);
if($term_array == array()){
//empty term ..
$term->name = $my_term_name;
$term->vid = 1;
taxonomy_term_save($term);
$term_array = taxonomy_get_term_by_name($my_term_name);
}
//get the first index of the array .
foreach ($term_array as $tid => $term_object)break;
$node->field_tag['und'][$tid] = (array)$term_object;
Perhaps my experience is unique, but I found that using
$term = taxonomy_get_term_by_name($tag)
$tid = $term->tid;
caused an error.
I found that after $term is saved, there is no need to fetch the newly created term.
The $term object is updated to include the new tid.
Any answer that use LANGUAGE_NONE or 'und' to alter a field is not the proper way of doing it as it assumes that the drupal site is one language. The proper way to edit a field is to use entity_metadata_wrapper.
$node_wrapper = entity_metadata_wrapper('node', $node);
// If you have Entity API [entity] module installed you can simply.
$node_wrapper = $node->wrapper();
// It is good practice to check the terms in the field before adding
// a new one to make sure that the term is not already set.
$term_ids_current = $node_wrapper->taxonomy_catalog->raw();
if (!in_array($term_new_id, $term_ids_current)) {
$node_wrapper->taxonomy_catalog[] = $term_new_id;
}
// To add multiple terms iterate an array or terms ids.
$term_ids_current = $node_wrapper->taxonomy_catalog->raw();
$tern_new_ids = array(1, 2, 3);
foreach ($term_new_ids as $term_new_id) {
if (!in_array($term_new_id, $term_ids_current)) {
$node_wrapper->taxonomy_catalog[] = $term_new_id;
}
}
// To remove a term.
$term_ids_current = $node_wrapper->taxonomy_catalog->raw();
$delta = array_search($term_remove_id, $term_ids_current);
if (is_int($delta)) {
$node_wrapper->taxonomy_catalog->offsetUnset($delta);
}
// To replace all terms.
$term_new_ids = array(1, 2, 3);
$node_wrapper->taxonomy_catalog->set($term_new_ids);
// To get all the fully loaded terms in a field.
$terms = $node_wrapper->taxonomy_catalog->value();
// At the end make sure to save it.
$node_wrapper->save();
I have been going through the docs and source code looking for something without luck.
Is there a Drupal 6 hook that gets called after hook_search(), but before the $results gets handed off to the template system?
I need to do a fairly custom pruning and reordering of results that get returned. I could just reimplement hook_search(), but this seems like overkill.
Thanks.
There isn't; search_view() (which displays the results) calls search_data(), which invokes hook_search() then immediately themes the results. Re-implementing hook_search() is probably the most straightforward route.
With that said, you could instead implement hook_menu_alter() and have the search page call your custom function instead of calling search_view() (and subsequently calling search_data()). Something like:
function test_menu_alter(&$items) {
$items['search']['page callback'] = 'test_search_view';
foreach (module_implements('search') as $name) {
$items['search/' . $name . '/%menu_tail']['page callback'] = 'test_search_view';
}
}
// Note: identical to search_view except for --- CHANGED ---
function test_search_view($type = 'node') {
// Search form submits with POST but redirects to GET. This way we can keep
// the search query URL clean as a whistle:
// search/type/keyword+keyword
if (!isset($_POST['form_id'])) {
if ($type == '') {
// Note: search/node can not be a default tab because it would take on the
// path of its parent (search). It would prevent remembering keywords when
// switching tabs. This is why we drupal_goto to it from the parent instead.
drupal_goto('search/node');
}
$keys = search_get_keys();
// Only perform search if there is non-whitespace search term:
$results = '';
if (trim($keys)) {
// Log the search keys:
watchdog('search', '%keys (#type).', array('%keys' => $keys, '#type' => module_invoke($type, 'search', 'name')), WATCHDOG_NOTICE, l(t('results'), 'search/'. $type .'/'. $keys));
// Collect the search results:
// --- CHANGED ---
// $results = search_data($keys, $type);
// Instead of using search_data, use our own function
$results = test_search_data($keys, $type);
// --- END CHANGED ---
if ($results) {
$results = theme('box', t('Search results'), $results);
}
else {
$results = theme('box', t('Your search yielded no results'), search_help('search#noresults', drupal_help_arg()));
}
}
// Construct the search form.
$output = drupal_get_form('search_form', NULL, $keys, $type);
$output .= $results;
return $output;
}
return drupal_get_form('search_form', NULL, empty($keys) ? '' : $keys, $type);
}
// Note: identical to search_data() except for --- CHANGED ---
function test_search_data($keys = NULL, $type = 'node') {
if (isset($keys)) {
if (module_hook($type, 'search')) {
$results = module_invoke($type, 'search', 'search', $keys);
if (isset($results) && is_array($results) && count($results)) {
// --- CHANGED ---
// This dsm() is called immediately after hook_search() but before
// the results get themed. Put your code here.
dsm($results);
// --- END CHANGED ---
if (module_hook($type, 'search_page')) {
return module_invoke($type, 'search_page', $results);
}
else {
return theme('search_results', $results, $type);
}
}
}
}
}
You can use hook_search_page() to reorder or format the search result.
Hook search_execute allows you to modify the query in the way you needed. You can even fire new queries with custom sql, for example:
function mymodule_search_execute($keys = NULL, $conditions = NULL) {
// Do some query here.
$result = my_fancy_query();
// Results in a Drupal themed way for search.
$results[] = array(
'link' => (string) $result->U,
'title' => $title,
'snippet' => $snippet,
'keys' => check_plain($keys),
'extra' => array($extra),
'date' => NULL,
);
I was trying to do do a boolean search 'sname:'.$user->name.' OR sname:xxxxxx; , i am not getting any results where as sname:xxxxxx; works fine. i even added mm=1 with the query modify hook. can somebody guide me how i can accomplish this.
Here is my code.....
$keys = "";
$filters = 'sname:'.$user->name.' OR sname:xxxxxx;
//print($filters);
$solrsort = variable_get('apachesolr_search_taxonomy_sort', 'created desc');
$page = isset($_GET['page']) ? $_GET['page'] : 0;
$_GET['retain-filters'] = 1;
try {
//stolen from search.module (search_data)
$data = apachesolr_search_execute($keys, $filters, $solrsort, 'search/apachesolr_search', $page);
$results = theme('search_results', $data, $type);
} catch (Exception $e){
watchdog('apachesolr', t('Error running search'));
}
function reports_apachesolr_modify_query(&$query, &$params, $caller) {
// I only want to see articles by the admin!
$params['mm'] = 1;
}
Adv thanks.
The $user object is not available in some places, so it depends where you are calling it from. You need to invoke it globally. Add the following to the top of your code.
$keys = "";
global $user; //Add this line
$filters = 'sname:'.$user->name.' OR sname:xxxxxx';
Also note that you are missing a closing quotation mark after the xxxxxx. I added it in the above code.
Did you try removing the second sname:?? My SOLR filters look like:
(fname:carrie OR carol)
AND
(lname:miller OR jones)