wpallimport, run function 'dont_create_terms' only for specidied taxonomies - wordpress

So, prefix that my coding level is practically equal to zero...
I'm using Wordpress with Wp All Import plugin, and i have this code to prevent wpallimport to create new categories/taxonomies etc.
function dont_create_terms( $term_into, $tx_name ) {
// Check if term exists, checking both top-level and child
// taxonomy terms.
$term = empty($term_into['parent']) ? term_exists( $term_into['name'], $tx_name, 0 ) : term_exists( $term_into['name'], $tx_name, $term_into['parent'] );
// Don't allow WP All Import to create the term if it doesn't
// already exist.
if ( empty($term) and !is_wp_error($term) ) {
return false;
}
// If the term already exists assign it.
return $term_into;
}
add_filter( 'pmxi_single_category', 'dont_create_terms', 10, 2 );
Now, as specified in the title, i have to run this code only for certain taxonomies...
I have tried multiple solutions, for last i tried to add this line
if ($tx_name == 'taxonomyname') {
like here
function dont_create_terms( $term_into, $tx_name ) {
// Check if term exists, checking both top-level and child
// taxonomy terms.
$term = empty($term_into['parent']) ? term_exists( $term_into['name'], $tx_name, 0 ) : term_exists( $term_into['name'], $tx_name, $term_into['parent'] );
if ($tx_name == 'taxonomyname') {
// Don't allow WP All Import to create the term if it doesn't
// already exist.
if ( empty($term) and !is_wp_error($term) ) {
return false;
}
// If the term already exists assign it.
return $term_into;
}
add_filter( 'pmxi_single_category', 'dont_create_terms', 10, 2 );
but everytime nothing appens.
Any help is really appreciated, thanks to everyone in advance
Edit:
Solution found
function dont_create_terms( $term_into ) {
// Check if term exists, checking both top-level and child
// taxonomy terms.
$term = empty($term_into['parent']) ? term_exists( $term_into['name'], $tx_name, 0 ) : term_exists( $term_into['name'], $tx_name, $term_into['parent'] );
if ( $tx_name == 'taxonomy_name' ){
// Don't allow WP All Import to create the term if it doesn't
// already exist.
if ( empty($term) and !is_wp_error($term) ) {
return false;
}
// If the term already exists assign it.
return $term_into;
}
add_filter( 'pmxi_single_category', 'dont_create_terms', 10, 2 );
And than call the function:
[dont_create_terms({yourxmldata[1]})]
Edit 2
It only works with single taxonomies, if the taxonomies contain multiple values it will not work
So again, if you have any suggestions you are welcome

The right way to do this would be writing your our custom function as shown here: https://www.wpallimport.com/documentation/code-snippets/#reference-taxonomy-terms-by-custom-id
However, although it is not elegant at all, I have found a different solution that could work for some, which involves wp-all-import's [foreach()] function.
It is not flexible as it requires that you add the max amount of values possible in your file (e.g 6 values tops in this example):
[foreach( {ParentNode/CategoryNode} )] {#id} > {Value1} |
{#id} > {Value[2]} | {#id} > {Value[3]} | {#id} > {Value[4]} |
{#id} > {Value[5]} | {#id} > {Value[6]} | [endforeach]
Where {ParentNode/CategoryNode} + #id + Value represent this portion of the xml file:
<ParentNode>
<CategoryNode id="this-cat-id">
<Value>Your value here</Value>
</CategoryNode>
</ParentNode>
Important: This will generate this error log while importing, every time it tries to import a value that does not exist, but the import will still work:
WARNING: It is necessary to assign a name to this term.
Important:
(1) In the import settings, you will need to go to 'Taxonomies, Categories, Tags', and select 'An element in my file contains the entire hierarchy...'.
(2) Then, check 'Separate hierarchy groups via symbol'.
(3) Do not check 'Only assign Your-cat-name-goes-here to the bottom level term in the hierarchy'
Here is how I set it up....
Screenshot WPAllImport
Hope this helps newcomers!

Related

Woocommerce Add to cart function showing error

I am just using the below code. It was working fine but from today is shows error - "TypeError thrown wc_add_number_precision(): Argument #1 ($value) must be of type float, null given, called in /chroot/home/a23cc473/fdd76f6eaa.nxcli.net/html/wp-content/plugins/woocommerce/includes/wc-core-functions.php on line 1955". Here is my code - WC()->cart->add_to_cart( 5 )
Can anyone please advise me why this error is showing
It's related with newest WC core, go and edit wc->includes->wc-core-functions.php row 1918 and replace it with older function:
new (not working) :
function wc_add_number_precision( float $value, bool $round = true ) {
old (working one) :
function wc_add_number_precision( $value, $round = true ) {
It's not best fix, but at least is working.

get count with hasMany not working yii2

I have CLub model (clubs) hasMany with User model like
Club n-n User
and I have UserClub model with columns: id, club_id, user_id, etc
In Club model
public function getCountUsers()
{
return $this->hasMany(UserClub::className(), ['club_id'=>'id'])->count();
}
I wanna count all User on Club as code:
$query = Club::find()
->joinWith(['countUsers']);
// ->with('countUsers');
->all();
so it is not working and throwing an error
Club has no relation named \"countUsers\"."
Because it isn't a relation as it does not return a model object or an array of model objects, instead you are using ->count() that makes it return a string that contains the total count for the user against the club.
If you are looking to get a count for the users against all the Clubs you can use the currently defined relation like $club->countUser see below.
$clubs=Club::find()->all();
foreach($clubs as $club){
echo $club->countUser;
}
or change the relation to
public function getCountUser(){
return $this->hasMany(UserClub::className(), ['club_id'=>'id']);
}
and use it like
$clubs=Club::find()->all();
foreach($clubs as $club){
echo count($club->countUser);
}
or like below
$clubs=Club::find()->all();
foreach($clubs as $club){
echo $club->getCountUser()->count();
}
EDIT
You are actually trying to transform the following query using ActiveRecord as far as I understood from the discussion.
SELECT clubs.id, count(user_clubs.id) as total
FROM
clubs
left join user_clubs on clubs.id = user_clubs.club_id
group by clubs.id
if that is correct you can use the following
Clubs::find ()
->alias ( 'c' )
->select ( [ new \yii\db\Expression ( 'c.[[id]], count(uc.[[id]]) as total' ) ] )
->leftJoin ( '{{%user_clubs}} uc' , 'uc.club_id=c.id' )
->groupBy ( 'c.id' )
->all ();
Note : You have to do one more thing you have to add a public property $total inside your Club model and add it to safe rules, because you are selecting the count as an alias total and until unless you define it inside the model the result set won't show you the count, so add the following inside the Club model.
public $total;
under rules
[[other fields...,'total'] , 'safe' ] ,
EDIT2
For some reason, I have a feeling that you are trying to count by specifying a relation instead of specifying the ->leftJoin () with the table user_clubs in the query.
If that is so then you have to change your relation getUserCount() you should better give a meaningful name that describes it. i would rename it to getClubUsers()
public function getClubUsers(){
return $this->hasMany(UserClub::className(), ['club_id'=>'id']);
}
After this, you still have to declare a public property $total as I described before inside your Club model, and add it to safe rules.
Now you can write your query in the following way
Clubs::find ()
->alias ( 'c' )
->select ( [ new \yii\db\Expression ( 'c.[[id]], count(cu.[[id]]) as total' ) ] )
->joinWith( ['clubUsers cu'] )
->groupBy ( 'c.id' )
->all ();
You can do this with join, in my case i get users who have more than 0 referrals.
$users = User::find()->with('referrals')
->from(User::tableName() . ' t')
->join('left join',User::tableName().' r','r.Deeplink = t.ReferralID')
->select('t.*,count(r.ID) as ct')
->groupBy('t.ID')
->andFilterHaving(['>','ct',0])
->all();
Hi your relation is correct check you error Club has no relation named \"countUsers\"."
Means you are calling a relation which not exist :
change query like this, Relation name should be in Club Model
public function getCount(){
return $this->hasMany(UserClub::className(), ['club_id'=>'id']);
}
$clubs=Club::find()->all();
foreach($clubs as $club){
echo count($club->getCount);
}
$query = Club::find()
->joinWith(['count']);
// ->with('countusers');
->all();
If you want count just do like this .
Load the Club model .
$club_model = Club::find()
$count = club_model->count;

Algorithm to Save Items with Parent-Child Relationship to Database

I need help designing the logic of an app that I am working on.
The application should enable users to create mindmaps and save them to a mysql database for later editing.
Each mindmap is made up of inter-related nodes, meaning a node should have a parent node and the id of the mindmap to which it belongs.
I am stuck here. How can I save the nodes to the database and be able to query and rebuild the mindmap tree from the query results.
Root
Child1
Child2
GrandChild1
GreatGrandChild1
GreatGrandChild1
Child3
GrandChild2
I need an algorithm, that can save the nodes and also be able to figure out the relationships/order of items similar to the Tree that I have given. This is very much like how menus are saved and retrieved in Wordpress but I can't find the right logic to do this.
I know there are really great people here. Please help.
This is very easy in a 3 column table.
Column-1: id, Column-2: name, Column-3: parent_id
for example, the data would be like this:
1 ROOT NULL
2 Child1 1
3 Child2 1
... and so on..
I finally found a solution. Here's my full code.
require_once('config.php');//db conn
$connect = mysql_connect(DB_HOST, DB_USER, DB_PASS);
mysql_select_db(DB_NAME);
$nav_query = MYSQL_QUERY("SELECT * FROM `nodes` ORDER BY `id`");
$tree = ""; // Clear the directory tree
$depth = 1; // Child level depth.
$top_level_on = 1; // What top-level category are we on?
$exclude = ARRAY(); // Define the exclusion array
ARRAY_PUSH($exclude, 0); // Put a starting value in it
WHILE ( $nav_row = MYSQL_FETCH_ARRAY($nav_query) )
{
$goOn = 1; // Resets variable to allow us to continue building out the tree.
FOR($x = 0; $x < COUNT($exclude); $x++ ) // Check to see if the new item has been used
{
IF ( $exclude[$x] == $nav_row['id'] )
{
$goOn = 0;
BREAK; // Stop looking b/c we already found that it's in the exclusion list and we can't continue to process this node
}
}
IF ( $goOn == 1 )
{
$tree .= $nav_row['name'] . "<br>"; // Process the main tree node
ARRAY_PUSH($exclude, $nav_row['id']); // Add to the exclusion list
IF ( $nav_row['id'] < 6 )
{ $top_level_on = $nav_row['id']; }
$tree .= build_child($nav_row['id']); // Start the recursive function of building the child tree
}
}
FUNCTION build_child($oldID) // Recursive function to get all of the children...unlimited depth
{
$tempTree='<ul>';
GLOBAL $exclude, $depth; // Refer to the global array defined at the top of this script
$child_query = MYSQL_QUERY("SELECT * FROM `nodes` WHERE parent_id=" . $oldID);
WHILE ( $child = MYSQL_FETCH_ARRAY($child_query) )
{
IF ( $child['id'] != $child['parent_id'] )
{
FOR ( $c=0;$c<$depth;$c++ ) // Indent over so that there is distinction between levels
{ $tempTree .= " "; }
$tempTree .= "<li>" . $child['name'] . "</li>";
$depth++; // Incriment depth b/c we're building this child's child tree (complicated yet???)
$tempTree .= build_child($child['id']); // Add to the temporary local tree
$depth--; // Decrement depth b/c we're done building the child's child tree.
ARRAY_PUSH($exclude, $child['id']); // Add the item to the exclusion list
}
}
RETURN $tempTree.'</ul>'; // Return the entire child tree
}
ECHO $tree;
?>
This is based on the piece of code found here http://psoug.org/snippet/PHP-Recursive-function-to-generate-a-parentchild-tree_338.html I hope this helps someone as well

How to ignore a custom field value if its empty

I have five custom fields for loading images but all of them are not required. I mean the user can upload a random number of images from 1 to 5. I am stuck in a simple lack of concept here. How should I check if any of them is empty and discard it. More specifically I want to discard the non-existing fields and store only the uploaded ones in an array. Here is my code
$custom_fields = get_post_custom($id);
$my_custom_field1 = $custom_fields['image1'];
$my_custom_field2 = $custom_fields['image2'];
$my_custom_field3 = $custom_fields['image3'];
$my_custom_field4 = $custom_fields['image4'];
$my_custom_field5 = $custom_fields['image5'];
if(!(false===($my_custom_field1))) { $img[]=$my_custom_field1;}
if(!(false===($my_custom_field2))) { $img[]=$my_custom_field2;}
if(!(false===($my_custom_field3))) { $img[]=$my_custom_field3;}
if(!(false===($my_custom_field4))) { $img[]=$my_custom_field4;}
if(!(false===($my_custom_field5))) { $img[]=$my_custom_field5;}
$images = Array("image1","image2","image3","image4","image5");
foreach($images as $image){
if(isset($custom_fields[$image])){
$img[] = $custom_fields[$image];
}
}
Didn't tested that, but should work.
if(isset($my_custom_field5)){
// do something with $my_custom_field5
}
I would suggest using
if ( !empty($my_custom_field)){
\\Do Something
}
because isset only checks for variable beings set and not null where as empty checks if the variable is an empty string, false, array(), NULL, “0?, 0, and an unset variable.

Drupal: How to override a function from a contrib module

I am using a module that builds a price table for Drupal Commerce items. There is a function that formats the table headers:
/**
* Helper function that takes care of the quantity displayed in the headers of
* the price table.
*/
function commerce_price_table_display_quantity_headers($item) {
// Set the quantity text to unlimited if it's -1.
$max_qty = $item['max_qty'] == -1 ? t('Unlimited') : $item['max_qty'];
// If max and min qtys are the same, only show one.
if ($item['min_qty'] == $max_qty) {
$quantity_text = $item['min_qty'];
}
else {
$quantity_text = $item['min_qty'] . ' - ' . $max_qty;
}
return $quantity_text;
}
As you can see, this is not a theme function where I can override it in template.php but I can to tweak some of the output.
How can I redefine this function so I can chop and change a few things?
My work so far...
So far, I have tried to create it as a seperate module with a few subtle changes to show if it's working or not, but it's not overriding any of the output.
Info file
; $id$
name = Price Table: Tweaked Display
description = A different layout for the price table as shown on the product display nodes
package = Commerce (contrib)
core = 7.x
dependencies[] = commerce_product
dependencies[] = commerce_price
dependencies[] = commerce_price_table
Module File
/**
* Override of the helper function that takes care of the quantity displayed in the headers of
* the price table.
*/
function commerce_table_tweak_display_quantity_headers($item) {
// Set the quantity text to unlimited if it's -1.
$max_qty = $item['max_qty'] == -1 ? t('Unlimited gnhh') : $item['max_qty'];
// If max and min qtys are the same, only show one.
if ($item['min_qty'] == $max_qty) {
$quantity_text = $item['min_qty'];
}
else {
$quantity_text = $item['min_qty'] . ' - this is working - ' . $max_qty;
}
return $quantity_text;
}
Most drupal modules I believe have a hook_function (or at least ones that are hookable) I don't do this much so I would search the drupal api for how to hook functions and if your module will support it.

Resources