I'm creating a component in Joomla, where among other things, can create and update menus, and I have successfully used this answer to create a new menu item.
https://joomla.stackexchange.com/questions/5104/programmatically-add-menu-item-in-component?newreg=1e7c576205354c0795a55607bc3e2508
$menuTable = JTableNested::getInstance('Menu');
// which menu you want to add to -
$menutype = 'thisismymenusname';
// this is heading menu item but what data you have and require will vary per case - just look at an appropriate row in yr menu table
$menuData = array(
'menutype' => $menutype,
'title' => $table->alias,
'alias' => $table->alias,
'path' => $table->alias,
'type' => 'heading',
'component_id' => 0,
'language' => '*',
'published' => 1,
);
// this item is at the root so the parent id needs to be 1
$parent_id = 1;
$menuTable->setLocation($parent_id, 'last-child');
// save is the shortcut method for bind, check and store
if (!$menuTable->save($menuData))
{
$this->setError($menuTable->getError());
return false;
}
But I'm unable to find the correct way to update a menu item, like the title and alias. But it is unsuccessful. I have tried using this with no success.
$menu_title = $_POST['title'];
$menu_alias = JFilterOutput::stringURLSafe($menu_title);
$menuTable = JTableNested::getInstance('Menu');
// this is heading menu item but what data you have and require will vary per case - just look at an appropriate row in yr menu table
$menuData = array(
'title' => $menu_title,
'alias' => $menu_alias,
);
// this item is at the root so the parent id needs to be 1
$parent_id = ($_POST['parent'] != "" ? $_POST['parent'] : '1');
$menuTable->setLocation($parent_id, 'last-child');
// save is the shortcut method for bind, check and store
if (!$menuTable->set($_POST['menuid'],$menuData)) {
$this->setError($menuTable->getError());
exit;
}
Can anyone help?
Does anyone know of a way to display a random number between 190-250 inside a specific page?
For example:
Today I had Display Random Number Coffees.
The way I would accomplish this is with a shortcode, like this:
function na_random_number_shortcode( $atts ) {
global $post;
$args = shortcode_atts(
array(
'min' => 190,
'max' => 250,
'id' => $post->ID,
'hours' => 24
),
$atts, 'random_number'
);
// Use transient to store the random number temporarily
if ( false === ( $random_number = get_transient( 'random_number_'.$args['id'] ) ) ) {
$random_number = mt_rand( (int) $args['min'], (int) $args['max'] );
set_transient( 'random_number_'.$args['id'], $random_number, HOUR_IN_SECONDS * $args['hours'] );
}
return $random_number;
}
add_shortcode( 'random_number', 'na_random_number_shortcode' );
Putting that code in your theme's functions.php file would allow you to enter
"Today I had [random_number] Coffees."
and display a random number between 190 and 250.
It's also flexible; you can do something like [random_number min="1" max="10"] to get a random number between 1 and 10.
By default, it will remember the random number for 24 hours. You can change this by passing in the "hours" attribute, like: [random_number hours="12"]
If you have more than one of these on a page, and you want the numbers to be different, you have to give each one a unique id. So if you had two of them, you could do: [random_number id="1"] and [random_number id="2"]
You can also use the PHP rand function in the page where you want it:
echo(rand(190,250));
I am creating a plugin that ties into the Runit System for showing onhand products in WooCommerce. This requires changing products via a Cron job that will update them, from Simple Products to Variable Products and vice versa depending on the quantity of stock and the variations of these products, which change. I have working code, that updates these products in the backend, showing the correct variations, however, it does not update on the front end. The new variations, even when editing Variable Products, do not show on the front end when viewing the actual Product itself. I still see the old variations in there. How to update the variations to use the new variations automatically, instead of having to hit the Update button in the backend Administration when editing the Product?
Is there some sort of function that needs to be called for updating the Variations in WooCommerce that I'm not aware of? I am using the array like this and serializing it before updating the meta_value for the meta_key _product_attributes in wp_postmeta table, like so:
function ProcessBasicProperties(Array $properties)
{
$return = array();
$position = 0;
if (!empty($properties))
{
if (!empty($properties['siz']))
{
++$position;
$size = !is_array($properties['siz']) ? array($properties['siz']) : array_unique($properties['siz']);
$return['size'] = array(
'name' => 'Size',
'value' => count($size) > 1 ? implode(' | ', $size) : $size[0],
'is_visible' => count($size) > 1 ? 0 : 1,
'is_variation' => count($size) > 1 ? 1 : 0,
'is_taxonomy' => 0,
'position' => $position
);
}
if (!empty($properties['ext']))
{
++$position;
$extension = !is_array($properties['ext']) ? array($properties['ext']) : array_unique($properties['ext']);
$return['extension'] = array(
'name' => 'Extension',
'value' => count($extension) > 1 ? implode(' | ', $extension) : $extension[0],
'is_visible' => count($extension) > 1 ? 0 : 1,
'is_variation' => count($extension) > 1 ? 1 : 0,
'is_taxonomy' => 0,
'position' => $position
);
}
// styles do not get added to attributes for variable products, instead, with variable products, the style goes into the overall sku of the product (General Properties)
// So, in short, variable products should not have this key set.
if (!empty($properties['style']))
{
++$position;
$return['style'] = array(
'name' => 'Style',
'value' => htmlspecialchars($properties['style'], ENT_QUOTES),
'is_visible' => 1,
'is_variation' => 0,
'is_taxonomy' => 0,
'position' => $position
);
}
if (!empty($properties['color']))
{
++$position;
$colors = !is_array($properties['color']) ? array($properties['color']) : array_unique($properties['color']);
$return['color'] = array(
'name' => 'Color',
'value' => count($colors) > 1 ? htmlspecialchars(implode(' | ', $colors), ENT_QUOTES) : htmlspecialchars($colors[0], ENT_QUOTES),
'is_visible' => 1,
'is_variation' => 0,
'is_taxonomy' => 0,
'position' => $position
);
}
if (!empty($properties['gender']))
{
++$position;
$return['gender'] = array(
'name' => 'Gender',
'value' => htmlspecialchars($properties['gender'], ENT_QUOTES),
'is_visible' => 1,
'is_variation' => 0,
'is_taxonomy' => 0,
'position' => $position
);
}
if (!empty($properties['season']))
{
++$position;
$return['season'] = array(
'name' => 'Season',
'value' => htmlspecialchars($properties['season'], ENT_QUOTES),
'is_visible' => 1,
'is_variation' => 0,
'is_taxonomy' => 0,
'position' => $position
);
}
}
return $return;
}
This is a function that returns the proper array that get serialized and inputted into the wp_postmeta table for the meta_value where meta_key = _product_attributes. Each variation also has a meta_key of attribute_size and meta_key of attribute_extension where the meta_value equals the value of that specific variation as required within the wp_postmeta table for that posts variation ID.
I'm at a loss, trying to update the variations of a Variable Product, or when Converting a Simple Product to a Variable Product, that needs to be updated. It shows up fine in the backend admin panel of the product, but when going to the actual product page, it still shows the OLD product variations. The only way to show the new one's is to go into the backend admin panel of the product and hit the Update button, which than shows all of the new variations. But how to do this programmatically? I thought this was possible? Must be something I'm overlooking here? Perhaps there are terms somewhere that need updating?
Functions that I have tried, that failed to update the product with the new variations, s for small = variation id 181342 and l for large = variation id 181343 from ID column of of wp_posts table or post_id column of the wp_postmeta table for that Variation:
wp_set_object_terms(181342, 's', 'size');
wp_set_object_terms(181343, 'l', 'size');
and
do_action( 'woocommerce_create_product_variation', 181342 );
do_action( 'woocommerce_create_product_variation', 181343 );
None of these update the product as a variation that shows on the front end. It still shows ONLY the old variations on the front end. How to get the size s and l showing on the front end?
Figured it out... looks like you have to update the wp_options table using set_transient... Here's what I did and it nipped it in the bud:
$transients = array(
'name' => array(
'wc_product_total_stock_' . $product_id,
'wc_product_children_ids_' . $product_id
),
'values' => array(
$total_stock,
$allVariationIDs
),
'filters' => array(
'woocommerce_stock_amount'
)
);
// Set it up so that the variations show in the front end also...
foreach($transients['name'] as $k => $transient_name)
{
set_transient($transient_name, $transients['values'][$k],YEAR_IN_SECONDS);
if (isset($transients['filters'][$k]))
apply_filters($transients['filters'][$k], $transients['values'][$k]);
}
$product_id = the actual products ID value.
$allVariationIDs = an array of all ID values of the variations within the wp_posts table. $total_stock is the new stock of the product, calculating in all variation stock levels.
Hope this helps someone else to update their variations on the front end, after setting up all wp_posts and wp_postmeta table rows for your products and variations.
Along with updating product attributes, you will also have to update the product variations from the database.
For example, while deleting the product variations, you will have to remove it from the wp_posts table
You can refer this link for more details
Woocommerce - Cannot delete a product variation
I'm working on a modified WordPress loop and I'm trying to achieve is a "sort of" multiple wordpress loops that will appear on my index file.
My goal is to create the following:
Loop #1: a WP loop that will display the (latest and the most recent published) post number 1, 2 & 3.
Loop #2: a WP loop that will display the (latest and the most recent published) post number 4, 5, 6, 7, 8 & 9
Loop #3: a WP loop that will display the (latest and the most recent published) post number 10, 11, 12 & 13
Loop #4: a WP loop that will display the (latest and the most recent published) post number 14 & 15
Loop #5: a WP loop that will display the all the remaining post (this excludes post #1 to 15, which was already displayed by the Loop#1-4).
*Loops 1-5 will be wrapped up in to one loop and will run in my index file.
I know, anyone can argue that I can do this in a simple wordpress loop. but the reason behind this is each Loops has it's own unique HTML Structure (this is actually my plan).
In the Loop #5, I have tried using the <?php query_posts('offset=15'); if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> BUT the problem with this approach is it didn't worked well with the WP pagination. The problem is the when I tried to move to the Next Page or, the same set of post will be displayed which is the post #16 etc.
I am seeking your help and assistance that anyone could provide. I am a noob in WP Loops and has a very basic skills PHP.
Thank you everyone for your help.
You best solution would be to do a single loop with if's and an iterator. Like so:
$i = 1;
while (have_posts()) {
if ($i <= 3) {
[...]
} elseif ($i <= 9) {
[...]
} elseif ($i <= 13) {
[...]
} elseif ($i <= 15) {
[...]
} else {
[...]
}
$i++;
}
I would suggest separating each segment into a function/method that you call in each if statement to help keep things neat, but that is your call.
You should structure your query like so:
$q1 = new WP_Query(array(
'post__in' => array(1, 2, 3)
);
if ($q1->have_posts()) while ($q1->have_posts()) : $q1->the_post();
the_content(); // Structure your output normally here
endwhile;
And repeat for other queries, changing the variable name (q1 here) for each of them. For #5 you can use the 'post__not_in' key. See WP_Query reference for more options.
Alternate solution
Since you need this only to display different HTML output you could do a single loop, and conditionally insert different outputs according to the post id, like so:
if(have_posts()) while(have_posts()) : the_post();
switch(get_the_ID()) {
case 1: case 2: case 3:
// output for #1
break;
case 4: case 5: case 6: // ....
// output for #2
break;
default: // anything greater than 6 here
// default output
break;
}
endwhile;
See these all supported arguments for WP_Query OR query_posts
$args = array(
//////Author Parameters - Show posts associated with certain author.
'author' => 1,2,3, //(int) - use author id [use minus (-) to exclude authors by ID ex. 'author' => -1,-2,-3,]
'author_name' => 'luetkemj', //(string) - use 'user_nicename' (NOT name)
//////Category Parameters - Show posts associated with certain categories.
'cat' => 5,//(int) - use category id.
'category_name' => 'staff', 'news', //(string) - use category slug (NOT name).
'category__and' => array( 2, 6 ), //(array) - use category id.
'category__in' => array( 2, 6 ), //(array) - use category id.
'category__not_in' => array( 2, 6 ), //(array) - use category id.
//////Tag Parameters - Show posts associated with certain tags.
'tag' => 'cooking', //(string) - use tag slug.
'tag_id' => 5, //(int) - use tag id.
'tag__and' => array( 2, 6), //(array) - use tag ids.
'tag__in' => array( 2, 6), //(array) - use tag ids.
'tag__not_in' => array( 2, 6), //(array) - use tag ids.
'tag_slug__and' => array( 'red', 'blue'), //(array) - use tag slugs.
'tag_slug__in' => array( 'red', 'blue'), //(array) - use tag slugs.
//////Taxonomy Parameters - Show posts associated with certain taxonomy.
//Important Note: tax_query takes an array of tax query arguments arrays (it takes an array of arrays)
//This construct allows you to query multiple taxonomies by using the relation parameter in the first (outer) array to describe the boolean relationship between the taxonomy queries.
'tax_query' => array( //(array) - use taxonomy parameters (available with Version 3.1).
'relation' => 'AND', //(string) - Possible values are 'AND' or 'OR' and is the equivalent of ruuning a JOIN for each taxonomy
array(
'taxonomy' => 'color', //(string) - Taxonomy.
'field' => 'slug', //(string) - Select taxonomy term by ('id' or 'slug')
'terms' => array( 'red', 'blue' ), //(int/string/array) - Taxonomy term(s).
'include_children' => true, //(bool) - Whether or not to include children for hierarchical taxonomies. Defaults to true.
'operator' => 'IN' //(string) - Operator to test. Possible values are 'IN', 'NOT IN', 'AND'.
),
array(
'taxonomy' => 'actor',
'field' => 'id',
'terms' => array( 103, 115, 206 ),
'include_children' => false,
'operator' => 'NOT IN'
)
),
//////Post & Page Parameters - Display content based on post and page parameters.
'p' => 1, //(int) - use post id.
'name' => 'hello-world', //(string) - use post slug.
'page_id' => 1, //(int) - use page id.
'pagename' => 'sample-page', //(string) - use page slug.
'pagename' => 'contact_us/canada', //(string) - Display child page using the slug of the parent and the child page, separated ba slash
'post_parent' => 1, //(int) - use page id. Return just the child Pages.
'post__in' => array(1,2,3), //(array) - use post ids. Specify posts to retrieve.
'post__not_in' => array(1,2,3), //(array) - use post ids. Specify post NOT to retrieve.
//NOTE: you cannot combine 'post__in' and 'post__not_in' in the same query
//////Type & Status Parameters - Show posts associated with certain type or status.
'post_type' => array( //(string / array) - use post types. Retrieves posts by Post Types, default value is 'post';
'post', // - a post.
'page', // - a page.
'revision', // - a revision.
'attachment', // - an attachment. The default WP_Query sets 'post_status'=>'published', but atchments default to 'post_status'=>'inherit' so you'll need to set the status to 'inherit' or 'any'.
'my-post-type', // - Custom Post Types (e.g. movies)
),
'post_status' => array( //(string / array) - use post status. Retrieves posts by Post Status, default value i'publish'.
'publish', // - a published post or page.
'pending', // - post is pending review.
'draft', // - a post in draft status.
'auto-draft', // - a newly created post, with no content.
'future', // - a post to publish in the future.
'private', // - not visible to users who are not logged in.
'inherit', // - a revision. see get_children.
'trash' // - post is in trashbin (available with Version 2.9).
),
//NOTE: The 'any' keyword available to both post_type and post_status queries cannot be used within an array.
'post_type' => 'any', // - retrieves any type except revisions and types with 'exclude_from_search' set to true.
'post_status' => 'any', // - retrieves any status except those from post types with 'exclude_from_search' set to true.
//////Pagination Parameters
'posts_per_page' => 10, //(int) - number of post to show per page (available with Version 2.1). Use 'posts_per_page'=-1 to show all posts. Note if the query is in a feed, wordpress overwrites this parameter with the stored 'posts_per_rss' option. Treimpose the limit, try using the 'post_limits' filter, or filter 'pre_option_posts_per_rss' and return -1
'posts_per_archive_page' => 10, //(int) - number of posts to show per page - on archive pages only. Over-rides showposts anposts_per_page on pages where is_archive() or is_search() would be true
'nopaging' => false, //(bool) - show all posts or use pagination. Default value is 'false', use paging.
'paged' => get_query_var('page'), //(int) - number of page. Show the posts that would normally show up just on page X when usinthe "Older Entries" link.
//NOTE: You should set get_query_var( 'page' ); if you want your query to work with pagination. Since Wordpress 3.0.2, you dget_query_var( 'page' ) instead of get_query_var( 'paged' ). The pagination parameter 'paged' for WP_Query() remains the same.
//////Offset Parameter
'offset' => 3, //(int) - number of post to displace or pass over.
//////Order & Orderby Parameters - Sort retrieved posts.
'order' => 'DESC', //(string) - Designates the ascending or descending order of the 'orderby' parameter. Defaultto 'DESC'.
//Possible Values:
//'ASC' - ascending order from lowest to highest values (1, 2, 3; a, b, c).
//'DESC' - descending order from highest to lowest values (3, 2, 1; c, b, a).
'orderby' => 'date', //(string) - Sort retrieved posts by parameter. Defaults to 'date'.
//Possible Values://
//'none' - No order (available with Version 2.8).
//'ID' - Order by post id. Note the captialization.
//'author' - Order by author.
//'title' - Order by title.
//'date' - Order by date.
//'modified' - Order by last modified date.
//'parent' - Order by post/page parent id.
//'rand' - Random order.
//'comment_count' - Order by number of comments (available with Version 2.9).
//'menu_order' - Order by Page Order. Used most often for Pages (Order field in the EdiPage Attributes box) and for Attachments (the integer fields in the Insert / Upload MediGallery dialog), but could be used for any post type with distinct 'menu_order' values (theall default to 0).
//'meta_value' - Note that a 'meta_key=keyname' must also be present in the query. Note alsthat the sorting will be alphabetical which is fine for strings (i.e. words), but can bunexpected for numbers (e.g. 1, 3, 34, 4, 56, 6, etc, rather than 1, 3, 4, 6, 34, 56 as yomight naturally expect).
//'meta_value_num' - Order by numeric meta value (available with Version 2.8). Also notthat a 'meta_key=keyname' must also be present in the query. This value allows for numericasorting as noted above in 'meta_value'.
//'post__in' - Preserve post ID order given in the post__in array (available with Version 3.5).
//////Sticky Post Parameters - Show Sticky Posts or ignore them.
'ignore_sticky_posts' => false, //(bool) - ignore sticky posts or not. Default value is false, don't ignore. Ignore/excludsticky posts being included at the beginning of posts returned, but the sticky post will still be returned in the natural order othat list of posts returned.
//NOTE: For more info on sticky post queries see: http://codex.wordpress.org/Class_Reference/WP_Query#Sticky_Post_Parameters
//////Time Parameters - Show posts associated with a certain time period.
'year' => 2012, //(int) - 4 digit year (e.g. 2011).
'monthnum' => 3, //(int) - Month number (from 1 to 12).
'w' => 25, //(int) - Week of the year (from 0 to 53). Uses the MySQL WEEK command. The mode is dependenon the "start_of_week" option.
'day' => 17, //(int) - Day of the month (from 1 to 31).
'hour' => 13, //(int) - Hour (from 0 to 23).
'minute' => 19, //(int) - Minute (from 0 to 60).
'second' => 30, //(int) - Second (0 to 60).
//////Custom Field Parameters - Show posts associated with a certain custom field.
'meta_key' => 'key', //(string) - Custom field key.
'meta_value' => 'value', //(string) - Custom field value.
'meta_value_num' => 10, //(number) - Custom field value.
'meta_compare' => '=', //(string) - Operator to test the 'meta_value'. Possible values are '!=', '>', '>=', '<', or ='. Default value is '='.
'meta_query' => array( //(array) - Custom field parameters (available with Version 3.1).
array(
'key' => 'color', //(string) - Custom field key.
'value' => 'blue' //(string/array) - Custom field value (Note: Array support is limited to a compare value of 'IN', 'NOT IN', 'BETWEEN', or 'NOT BETWEEN')
'type' => 'CHAR', //(string) - Custom field type. Possible values are 'NUMERIC', 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED'. Default value is 'CHAR'.
'compare' => '=' //(string) - Operator to test. Possible values are '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'. Default value is '='.
),
array(
'key' => 'price',
'value' => array( 1,200 ),
'compare' => 'NOT LIKE'
)
//////Permission Parameters - Display published posts, as well as private posts, if the user has the appropriate capability:
'perm' => 'readable' //(string) Possible values are 'readable', 'editable' (possible more ie all capabilitiealthough I have not tested)
//////Parameters relating to caching
'no_found_rows' => false, //(bool) Default is false. WordPress uses SQL_CALC_FOUND_ROWS in most queries in order timplement pagination. Even when you don’t need pagination at all. By Setting this parameter to true you are telling wordPress not tcount the total rows and reducing load on the DB. Pagination will NOT WORK when this parameter is set to true. For more informatiosee: http://flavio.tordini.org/speed-up-wordpress-get_posts-and-query_posts-functions
'cache_results' => true, //(bool) Default is true
'update_post_term_cache' => true, //(bool) Default is true
'update_post_meta_cache' => true, //(bool) Default is true
//NOTE Caching is a good thing. Setting these to false is generally not advised. For more info on usage see: http://codex.wordpresorg/Class_Reference/WP_Query#Permission_Parameters
//////Search Parameter
's' => $s, //(string) - Passes along the query string variable from a search. For example usage see: http://www.wprecipes.com/how-to-display-the-number-of-results-in-wordpress-search
'exact' => true //(bool) - flag to make it only match whole titles/posts - Default value is false. For more information see: https://gist.github.com/2023628#gistcomment-285118
'sentance' => true //(bool) - flag to make it do a phrase search - Default value is false. For more information see: https://gist.github.com/2023628#gistcomment-285118
//////Post Field Parameters
//Not sure what these do. For more info see: http://codex.wordpress.org/Class_Reference/WP_Query#Post_Field_Parameters
//////Filters
//For more information on available Filters see: http://codex.wordpress.org/Class_Reference/WP_Query#Filters
);
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
// Do Stuff
endwhile;
endif;
// Reset Post Data
wp_reset_postdata();
This will help you to query anything.
Hope it will help you.
I'm editing my invoices file in
/Mage/Sales/Model/Order/Pdf/Items/Invoice/Default.php
And I'm running into a problem with columns running into and overlapping other columns if they have long content. eg Product description running over the next column. I'm trying to figure out how to limit the width / word wrap / create a new line for content.
Code is:
// draw Product name
$lines[0] = array(array(
'text' => Mage::helper('core/string')->str_split($item->getName(), 60, true, true),
'feed' => 35,
));
// draw SKU
// $lines[0][] = array(
// 'text' => Mage::helper('core/string')->str_split($this->getSku($item), 25),
// 'feed' => 255
// );
// draw Brand (Added by James)
$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $this->getSku($item), array('manufacturer'));
if ($product) {
$lines[0][] = array(
'text' => Mage::helper('core/string')->str_split($product->getAttributeText('manufacturer'), 15),
'feed' => 220
);
}
// draw Colour (Added by James)
$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $this->getSku($item), array('pos_short_colour'));
if ($product) {
$lines[0][] = array(
'text' => Mage::helper('core/string')->str_split($product->getAttributeText('pos_short_colour'), 15),
'feed' => 320
);
}
I know that 'feed' is what sets how far in from the left the array starts (pretty much = to a margin-left if all items were 'absolute' in css terms).
But I'm not sure how I can limit their width and word-wrap so that if I have a long manufacturer it won't run into the colour. There isn't enough space on the invoice to just simply give each attribute more room.
The answer was right there:
$lines[0] = array(array(
'text' => Mage::helper('core/string')->str_split($item->getName(), 60, true, true),
'feed' => 35,
));
The 60 here is how many characters will be displayed per line ->getName(), 60, true,
I had the same issue. When I added a new column, Product description column disappeared. I solved this by reducing a number (length) in str_split function of $productDescr.