I'm trying to retrieve the number of parking lots from a .txt file, its working on the static site iframe but I want to make a shortcode and place it on wordpress theme function file.
For some reason it's not reading the data...
function GenerateLOT($atts = array()) {
// Default Parameters
extract(shortcode_atts(array(
'id' => 'id'
), $atts));
// Create Default Park / Help
if ($id == '') {
$id = 'PARK IDs: bahnhofgarage;';
}
// Create Park Bahnhofgarage
if ($id == 'bahnhofgarage') {
$completeBahnhof = "//xxx.de/bahnhof.txt";
if(file_exists($completeBahnhof )) {
$fp=file($completeBahnhof );
$Garage = $fp[0];
$valmpl=explode(" ",$Garage);
$Bahnhof_Platz = $valmpl[0];
$Bahnhof_Tendenz = $valmpl[1];
}
$id = $Bahnhof_Platz;
}
return $id;
}
add_shortcode('parking', 'GenerateLOT');
[parking id='bahnhofgarage']
PS: The .txt is working properly retrieving like this: 000 - //bahnhof 27.12.15 12:46:59
For some reason its only displaying the $park == '' text and not the parking lots according shortcode param.
I've used this tutorial: sitepoint.com/wordpress-shortcodes-tutorial/
EDIT: There are 6 parking lots.
EDIT2: Changed park to id on all instances
The problem is that you can't meaningfully use file_exists on remote path. See SO answer to "file_exists() returns false even if file exist (remote URL)" question for details.
You should probably just call file() on that path. It will return FALSE if it encounter an error.
if ($id == 'bahnhofgarage') {
$completeBahnhof = "//xxx.de/bahnhof.txt";
$fp=file($completeBahnhof );
if ($fp !== false) {
$Garage = $fp[0];
// rest of code
On a side note, shortcode_atts() is used to provide default values for shortcode attributes, while you seem to be using it as some sort of mapping between shortcode attributes and internal variable names.
Accessing file on remote server inside shortcode is asking for trouble. Just think what will happen if this server is overloaded, slow to respond or not available anymore. You should really access that file asynchronously. If it is located on your server, access it through file-system path.
Related
Hello gods of Stackoverflow,
Now i hate to be "that guy" who didnt search properly but i am running into a problem that i need a fix for and can't find a solution i can work with because of my lack in coding skills, my knowledge barely tickles the surface.
Here's the thing.
I am using a tool to import feeds into my website (WP all Import) as woocommerceproducts. But in the categorization the feed suppliers made errors which i want to tackle without emailing them everytime i stumble upon one.
i.e: the title contains words like satchel, bag, clutch etc but the product is categorized as 'jewellery > earrings' in the CSV or XML.
The import tool will ask me where to find the product category, i point it to the node {category[1]}
But when the category is missing or faulty i want it to check the title for certain words, and if present change the value of it to that found word.
something like:
[if ({title[1]}contains "satchel") {
category = "bags > satchel",
} else if ({title[1]} contains clutch) {
category = "bags > clutch",
} else {
category = {sub_category[1]} #the normal value if nothing was found
}]
I just can't find the pieces to put the formatting together. I might need to work towards a function that i could expand to generate categories based solely out of presence of certain words in the title but maybe when i get better that would be an option.
I hope i was able to provide a clear view on the problem. The "[ ]" is there because thats how the plugin wants code to be entered instead of a {fieldname[1]}, another example below:
The following was an example of a problem i was able to fix:
i needed to replace values like "0/3months/1/2months" to "0-3 months/1-2months" before i replaced the slash"/" with a pipe"|" for wordpress to recognize it as a seperate value.
[str_replace("/","|",
str_replace("0/3","0-3",
str_replace("1/2","1-2",
str_replace("3/6","3-6",{size[1]}))))]
The fields can also be used to call functions but only in the 'pro' version of the plugin.
Any help is very much appreciated, thanks in advance.
You could use strpos.
Example:
if (strpos($title, "satchel") !== false) {
$category = "bags > satchel";
}
So after an afternoon of poking around, testing stuff, and not knowing alot about php i came up with a solution with help from a friend.
Wp All Import does not allow custom php directly from the field itself, it does however support custom php functions and provides an editor for these on the bottom of the import configuration page. I did the following:
<?php
//Checks Title for keywords and
//uses those to create categories
//We are using our own Main categories so only
//sub and subsub categroies need to be created.
//Call function
[get_subcat_from_title({title[1]},{category[1]})]
//Function
function get_subcat_from_title($title,$defaultcat)
{
if (strpos($title,"Satchel") !== false) {
$cat = "Tassen";
} elseif (strpos($title,"Travel") !== false) {
$cat = "Tassen";
} elseif (strpos($title,"Gusset") !== false) {
$cat = "Tassen";
} else {
$cat = $defaultcat;
}
return $cat;
}
//Checks Title for keywords and uses those to create subcategories
//Call Function
[get_subsubcat_from_title({title[1]},{sub_category[1]})]
//Function
function get_subsubcat_from_title($title,$defaultcat)
{
if (strpos($title,"Satchel") !== false) {
$cat = "Satchel";
} elseif (strpos($title,"Travel") !== false) {
$cat = "Travel";
} elseif (strpos($title,"Gusset") !== false) {
$cat = "Gusset";
} else {
$cat = $defaultcat;
}
return $cat;
}
?>
On the Taxonomies, Tags, Categories option we can create our own hierarchical order like this:
[main category]
+[sub category]
++[sub sub category]
The main category field is given a name we use as our main category.
The sub category is filled with function SUBCAT
The subsub category is filled with function SUBSUBCAT
this way it will create a parent by our own name, a child that has the named 'Tassen' if any keyword is present, and a grandchild with the specific keyword as it's name.
This way i can expand the function using all kinds of statements when the right category isn't present in de provided feed.
thanks #sebastianForsberg for responding.
I hope this helps anyone who comes across a similar problem in the future..
I have the below function to create active trail functionality. So if I were to have /blog as a "parent" and a post of /blog/mypost, when on mypost the blog link would show as highlighted. I don't want to have to make menu items for all the blog posts. The problem is when caching is turned on (not using settings.local.php and debug turned off) the getRequestUri isn't changing on some pages. It seems to be cached depending on the page. It works fine with page caching turned off but I'd like to get this working with caching. Is there a better way to check for the current path and apply the active class?
function mytheme_preprocess_menu(&$variables, $hook) {
if($variables['theme_hook_original'] == 'menu__main'){
$node = \Drupal::routeMatch()->getParameter('node');
if($node){
$current_path = \Drupal::request()->getRequestUri();
$items = $variables['items'];
foreach ($items as $key => $item) {
// If current path starts with a part of another path i.e. a parent, set active to li.
if (0 === strpos($current_path, $item['url']->toString())) {
// Add active link.
$variables['items'][$key]['attributes']['class'] .= ' menu-item--active-trail';
}
}
}
}
}
I've also tried putting this into a module to try and see if I can get the current path to then do the twig logic in the menu--main.twig.html template but I have the same problem.
function highlight_menu_sections_template_preprocess_default_variables_alter(&$variables) {
$variables['current_path'] = $_SERVER['REQUEST_URI'];
}
After a very long time trying all sorts of things, I found an excellent module which addresses exactly this problem. Install and go, not configuration, it just works:
https://www.drupal.org/project/menu_trail_by_path
Stable versions for D7 and D8.
I tried declaring an active path as part of a custom menu block, and even then my declared trail gets cached. Assuming it's related to the "There is no way to set the active link - override the service if you need more control." statement in this changelog, though why MenuTreeParameters->setActiveTrail() exists is anybody's guess.
For the curious (and for me when I search for this later!), here's my block's build() function:
public function build() {
$menu_tree = \Drupal::menuTree();
$parameters = new MenuTreeParameters();
$parameters->setRoot('menu_link_content:700c69e6-785b-4db7-be49-73188b47b5a3')->setMinDepth(1)->setMaxDepth(1)->onlyEnabledLinks();
// An array of routes and menu_link_content ids to set as active
$define_active_mlid = array(
'view.press_releases.page_1' => 385
);
$route_name = \Drupal::request()->get(RouteObjectInterface::ROUTE_NAME);
if (array_key_exists($route_name, $define_active_mlid)) {
$menu_link = \Drupal::entityTypeManager()->getStorage('menu_link_content')->loadByProperties(array('id' => $define_active_mlid[$route_name]));
$link = array_shift($menu_link);
$parameters->setActiveTrail(array('menu_link_content:' . $link->uuid()));
}
$footer_tree = $menu_tree->load('footer', $parameters);
$manipulators = array(
array('callable' => 'menu.default_tree_manipulators:checkAccess'),
array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
);
$tree = $menu_tree->transform($footer_tree, $manipulators);
$menu = $menu_tree->build($tree);
return array(
'menu' => $menu,
);
}
[adding a new answer since this is a completely different approach than my earlier one]
If a CSS-based solution is acceptable, this seems to work okay:
.page-node-type-press-release {
a[data-drupal-link-system-path="press-room/press-releases"] {
// active CSS styles here
}
}
hi i've got a gallery page. this gallery page has a gallery image object with an has_many relation.
private static $has_many = array(
'GalleryImages' => 'GalleryObject'
);
my gallery object has an image upload field. I want to set the upload folder to the title of the gallery page
i tried this with no result
$visual->setFolderName('Galerie/'.$this->Gallery()->Title);
and this (what i would prefer)
public function getGalleryTitle() {
$galleryTitle = $this->Gallery()->Title->First();
$uploadFolder = str_replace(' ', '-', $this->$galleryTitle);
return $uploadFolder;
}
$visual->setFolderName('Galerie/'.$this->$uploadFolder);
the second returns and error (undefined variable uploadFolder ?!) and my upload folder is now set to "Galerie/DataList"
can someone tell me how to convert the output of $uploadFolder so that i get back the title?
EDIT:
GalleryHolder: http://www.sspaste.com/paste/show/5267dea3579a6
GalleryPage: http://www.sspaste.com/paste/show/5267dee4c9752
GalleryObject: http://www.sspaste.com/paste/show/5267df0af1a65
you where almost there..
Here is your edited getGalleryTitle() function.
It is basically checking if the GalleryObject has a parent Gallery via $this->GalleryID. Since it is a has_one relation the column will be named GalleryID.
Then we get the Gallery object with $this->Gallery() and get it's title with $gallery->Title.
I've also replaced your str_replace with SilverStripe's URLSegmentFilter class. Which will removed spaces and other special characters non welcome in URL, a better solution.
public function getGalleryTitle()
{
if ( $this->GalleryID )
{
$gallery = $this->Gallery();
$filter = new URLSegmentFilter();
return $filter->filter( $gallery->Title );
}
else{
return 'default';
}
}
Then in the getCMSFields() function, when creating your UploadField we just call the getGalleryTitle() function that returns the string for the folder name.
$visual = new UploadField('Visual', _t('Dict.IMAGE', 'Image'));
$visual->setFolderName('Galerie/'.$this->getGalleryTitle());
A few notes..
$this references the current Object instance, so you can't use $this->$galleryTitle to access a variable you just created in your function, $galleryTitle by itself is enough.
You were calling $this->$uploadFolder in setFolderName, this doesn't work for the same reason, and also, using $uploadFolder by itself wouldn't work since this variable was created in the scope of another function. So we just call the function we defined on our Object with $this->getGalleryTitle() since it returns the value we want.
This should work fine, but keep in mind that if the Title of the Gallery changes at some point, the folder name will change too. So you might end up with images uploaded in many different folders for the same gallery... I personally wouldn't advise it, unless you implement some kind of "Title locking system" or some way to keep the "correct" or first "valid/acceptable" Gallery title in a separate object property that can't be edited and use this in the folder name.
I usually only use the ID in those case ($gallery->ID), as this will not change.
edit
Another version of getGalleryTitle() that should work even if the GalleryObject isn't saved yet.
public function getGalleryTitle()
{
$parentID = Session::get('CMSMain')['currentPage'];
if ( $parentID )
{
$gallery = Page::get()->byID( $parentID );
$filter = new URLSegmentFilter();
return $filter->filter( $gallery->Title );
}
else{
return 'default';
}
}
First, I check to see whether we're on the CMSSettingsPage or in a ModelAdmin page (Should you be using them). You want to get all the information about which class the controller is managing as it's data record. (If you have firebug, FB($this) in getCMSFields() on the related DataObject (DO) will show you the page managed under DataRecord)
Controller::curr()->currentPage() will get you the current page the DO is being managed on, and ->URLSegment will get the page url name, though you could use Title or MenuTitle also.
Here is an example which will set up a folder underneath assets/Headers to save images in. Running this on the HomePage (ie URL Segment 'home') will create and save objects into the folder /assets/Headers/home.
if (Controller::curr()->class == 'CMSSettingsController' || Controller::curr() instanceof Modeladmin) {
$uploadField->setFolderName('Headers');
}
else
{
$uploadField->setFolderName('Headers/' . Controller::curr()->currentPage()->URLSegment);
}
I have created my own component. When I add a new record to my component, I also want it to create a new article in joomla (i.e. using com_content).
I found this on stack overflow Programmatically adding an article to Joomla which explains how to do it. The code makes sense, and looks like it will work. The problem is that once methods start being called that are contained in com_content, all the relative URLs in com_content break down and joomla throws an error.
Does anyone know a way to overcome this? A comment from the link above suggests that changing the current working directory to the com_content one before including it will work, but I'm not 100% sure on how to do this.
It's not possible to change the working directory because its a constant. To work around this issue you could choose not to use ContentModelArticle at all and instead use the table class only:
$table = JTable::getInstance('Content', 'JTable', array());
$data = array(
'catid' => 1,
'title' => 'SOME TITLE',
'introtext' => 'SOME TEXT',
'fulltext' => 'SOME TEXT',
'state' => 1,
);
// Bind data
if (!$table->bind($data))
{
$this->setError($table->getError());
return false;
}
// Check the data.
if (!$table->check())
{
$this->setError($table->getError());
return false;
}
// Store the data.
if (!$table->store())
{
$this->setError($table->getError());
return false;
}
Note that the code above does not trigger the before/after save events. If that is needed however, it should not be a problem to trigger those events. Also worth noticing is that the field published_up will not be automatically set and the articles within the category will not be reordered.
To reorder the category:
$table->reorder('catid = '.(int) $table->catid.' AND state >= 0');
The error I get says:
File not found /var/www/administrator/com_mynewcomponent/helpers/content.php
I got around the problem by creating an empty file at this location to suppress the error message and manually including /var/www/administrator/com_content/helpers/content.php with a require_once statement.
Support Joomla 2.5 and Joomla 3.0
JTableContent is not autoloaded prior to Joomla! version 3.0, so it needs to included:
if (version_compare(JVERSION, '3.0', 'lt')) {
JTable::addIncludePath(JPATH_PLATFORM . 'joomla/database/table');
}
$article = JTable::getInstance('content');
$article->title = 'This is my super cool title!';
$article->alias = JFilterOutput::stringURLSafe('This is my super cool title!');
$article->introtext = '<p>This is my super cool article!</p>';
$article->catid = 9;
$article->created = JFactory::getDate()->toSQL();
$article->created_by_alias = 'Super User';
$article->state = 1;
$article->access = 1;
$article->metadata = '{"page_title":"","author":"","robots":""}';
$article->language = '*';
// Check to make sure our data is valid, raise notice if it's not.
if (!$article->check()) {
JError::raiseNotice(500, $article->getError());
return FALSE;
}
// Now store the article, raise notice if it doesn't get stored.
if (!$article->store(TRUE)) {
JError::raiseNotice(500, $article->getError());
return FALSE;
}
I made a private section on a drupal site by writing a module that checks the RERQUEST_URI for the section as well as user role. The issue I am running into now is how to prevent those nodes/views from appearing in the search.
The content types used in the private section are used in other places in the site.
What's the best way to get Druapl search to ignore the content/not index/not display it in search results?
There is a wonderful article that explains just this on the lullabot site.
It's worth reading the comments to the post too, because people there suggested alternate ways of doing that, also by mean of contrib modules (rather than implementing some hooks in your own code). Code for D6 is in the comment as well.
HTH!
The lullabot article is a bit outdated and contains many blunt approaches. It also contains the answer in the comments - the Search Restrict module which works for DP6 and allows fine-grained and role-based control. Everything else either prevents content from being indexed, which may not be desirable if there are different access levels to content, or affects all search queries equally, which will also not work if there are different access levels.
If the content types used within the Private section are also used elsewhere how are you hoping to filter them out of the search results (note that I've not looked at the lullabot article by mac yet).
Basically, if you look at the details of two nodes, one private and one public, what differentiates them?
Note: I'm assuming that you want the nodes to appear to users with access to the Private area but not to 'anonymous' users.
For Drupal 7.
You can hide the node from search results by using custom field. In my case, I have created a custom field in the name of Archive to the desired content type and with the help of that custom field you can write the my_module_query_alter functionality.
Code
function my_module_query_alter(QueryAlterableInterface $query) {
$is_search = $is_node_search = FALSE;
$node_alias = FALSE;
foreach ( $query->getTables() as $table ) {
if ( $table['table'] == 'search_index' || $table['table'] == 'tracker_user') {
$is_search = TRUE;
}
if ( $table['table'] == 'node' || $table['table'] == 'tracker_user') {
$node_alias = $table['alias'];
$is_node_search = TRUE;
}
}
if ( $is_search && $is_node_search ) {
$nids = [];
// Run entity field query to get nodes that are 'suppressed from public'.
$efq = new EntityFieldQuery();
$efq->entityCondition('entity_type', 'node')
->fieldCondition('field_archive', 'value', 1, '=');
$result = $efq->execute();
if ( isset($result['node']) ) {
$nids = array_keys($result['node']);
}
if ( count($nids) > 0 ) {
$query->condition(sprintf('%s.nid', $node_alias), $nids, 'NOT IN');
}
}
}