how create read more function like wordpress in codeigniter - codeigniter

i have no idea how wordpress use <!--more--> to seperate the post then create read more link.
any idea?
thanks

Use the word_limiter() function from the Text Helper included in CodeIgniter to shorted your post to a fixed number of words, then append the "read more" hyperlink to that text, and echo.
Text Helper Reference

take a look in the WP source, the function is located in wp-includes/post-template.php around line 200 in the get_the_content function
I wouldn't recommend just copying and pasting as it likely won't work, but you may get the logic behind it. WP uses a preg_match for the <!--more --> tag, then parses it if it exists..
$content = $pages[$page-1];
if ( preg_match('/<!--more(.*?)?-->/', $content, $matches) ) {
$content = explode($matches[0], $content, 2);
if ( !empty($matches[1]) && !empty($more_link_text) )
$more_link_text = strip_tags(wp_kses_no_null(trim($matches[1])));
$hasTeaser = true;
} else {
// so on

Related

Laravel 8 multilanguage routes and how get the translated link of the same page

I'm trying to make my test app in multilanguage way.
This question has two correlated questions:
First question:
I followed the second answer in How to create multilingual translated routes in Laravel and this help me having a multilanguage site and the route cached, but I've a question and some misunderstanding.
It's a good practice overwrite an app config as they do int the AppServiceProver.php, making:
Config::set('app.locale_prefix', Request::segment(1));
Isn't better to work with the Session::locale in any case?
Second question:
In my case I've two languages, and in the navbar I want to print just ENG when locale is original language, and ITA when session locale is English.
If I'm in the Italian page, the ENG link in the navbar should point to the same English translated page.
Working with the method used in the other question, I hade many problems caused by the:
Config::set('app.locale_prefix', Request::segment(1));
We overwrite the variable in the config file local_prefix, and every time I switch to English language the locale_prefix will change to 'eng' and this sounds me strange, another thing I did is this:
if ( $lang && in_array($lang, config('app.alt_langs')) ){
return app('url')->route($lang . '_' . $name, $parameters, $absolute);
}
We use the alt_langs where are defined only the alternative languages, and this is a problem cause if I pass the local lang, in my case 'it', like lang parameter, this will not be found cause, from the description, the alt_lang should not contain the locale language and you will be able to get only the translated string.
If I change the:
if ( $lang && in_array($lang, config('app.alt_langs')) ){
return app('url')->route($lang . '_' . $name, $parameters, $absolute);
}
in:
if ( $lang && in_array($lang, config('app.all_langs')) ){
return app('url')->route($lang . '_' . $name, $parameters, $absolute);
}
Now using app.all_langs I'm able to choose which URL you want and in which language I want.
How do I get the translated URL?
In the blade file I need to get the translated URL of the page, and if read the other question, we used the $prefix for caching the routes and giving to the route a new name ->name($prefix.'_home'); in this way I can cache all the route and I can call the routes using blade without prefix {{ route('name') }} but, needing the translated url of the actual page a made this on the top of the view:
#php
$ThisRoute = Route::currentRouteName();
$result = substr($ThisRoute, 0, 2);
if ($result =='it' ){
$routeName = str_replace('it_', '', $ThisRoute);
$url = route($routeName,[],true,'en');
} else {
$routeName = str_replace('en_', '', $ThisRoute);
$url = route($routeName,[],true,'it');
}
#endphp
Doing this I get the actual route name that should be it_home I check if start with it_ or en_, I remove the it_ or en_ prefix and I get the translated URL, now you can use the $url as <a href="{{ $url" }}>text</a> cause if I call the {{ route('page') }} I get the link, with the locale language.
This code is not very good, I know, but I written in 5 minutes, need more implementation, and check, but for the moment is just to play with Laravel.
It's a good way?? How can I do it better (except the blade link retrieving)?? Many solution I found used middleware, but I would like to avoid a link in the navbar like mysite.com/changelang?lang=en
Is a good approach overriding the app.locale_prefix?
First
according to your question, it's a bad practice to save the preferences into .env or session because as soon as the session is finished the saved language will be removed also it's common when you need to store any preferences related to your website such as (Color, Font, Language, ...etc) you must store any of them into the cache.
Second
honestly, your code is a very strange and NOT common way and there are two ways to handle what do you need
First
There is a very helpful and awesome package called mcamara it'll help you too much (I recommend this solution).
Second
you can do it from scratch using the lang folder located in the resource folder and you must create files with the same count of the needed languages then use the keys that you'll define into these files into views and you can prefix your routes with the selected language you can use group method like so
Route::group(['prefix' => 'selected_lang'], function() {
Route::get('first_route', [Controller::class, 'your_method']);
});
or you can add the selected language as a query string like so localhost:8000/your_route?lang=en you can follow this tutorial for more info.

Getting Helper Data php in magento

Have been trying to get a variable percentage from two helper functions inside .phtml file in magento
basically i have two variables based on two helper functions that on their own output/echo static numbers. Problem is in the below php they are just displaying as the value and not dividing/multiplying. So like i said the helper data & module work is using the data as variables to do/complete the equation within the .phtml file. See code below
get->FunctionA() just equals a round number value (from a collection)
get->FunctionB() just equals a round number value as well (from a collection)
probs not the best way but this just outputs two values from helper data and not dividing.
echo Mage::helper('module/data')->getFunctionA() / Mage::helper('module/data')->getFunctionB();
Also this does not work either, just produces the same result and is probs the best/easiest way
$dataA = Mage::helper('module/data')->getFunctionA();
$dataB = Mage::helper('module/data')->getFunctionB();
$result = ($dataA / $dataB) * 100;
echo $result;
Like i said above the values can be echoed (in either helper function or phtml files but the actual calculation does not wont to work
Any help would be great
Ok sorted the problem out. What was happening was that in the helper file the getFunctionA() & getFunctionB() value was being echoed when i should have been just returning the value then echoing the helper function in the .phtml file. Doh! See below the helper function example that is now working Woohoo!!!
public function getFunctionA()
{
$FunctionA = Mage::getModel('module/collection')->getCollection();
$FunctionA->addFieldToFilter('attribute', 'value_to_filter');
$FunctionA->addFieldToFilter('status','1');
return ''.count($FunctionA) . ''; //this line was the problem cause i was echoing & not returning the value
}
Now the value can be echoed in the phtml & the math equation is confirmed working
$dataA = Mage::helper('module/data')->getFunctionA();
$dataB = Mage::helper('module/core')->getFunctionB();
$result = ($dataA / $dataB) * 100;
echo $result;
this code does the math and now i can rest.

Search specific text with DOM XPath

I have been trying to crawl a website pages and search for specific text using simple html dom and XPath. I have get all the links from website and trying to crawl that links and search text on all pages. The text that i want to search is within html span tag.
But no output is shown.
whats going wrong ?
here is my code
<?php
include_once("simple_html_dom.php");
set_time_limit(0);
$path='http://www.barringtonsports.com';
$html = file_get_contents($path);
$dom = new DOMDocument();
#$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");
for($i = 0; $i < $hrefs->length; $i++ ){
$href = $hrefs->item($i);
$url = $href->getAttribute('href');
$nurl = $path.$url;
$html1 = file_get_contents($nurl);
$dom1 = new DOMDocument();
#$dom1->loadHTML($html1);
$xpath1 = new DOMXPath($dom1);
$name = $xpath1->evaluate("//span[contains(.,'Asics Gel Netburner 15 Netball Shoes')]");
if($name)
echo"text found";
}
?>
I just want to check the whether text "Asics Gel Netburner 15 Netball Shoes" exist in any page of the website www.barringtonsports.com or not.
You're querying a lot of web-pages interactively. It takes more time than your server is allowed to use for generating pages.
You can execute this script from command-line to avoid timeouts or you can try to configure PHP and WebServer so they give more time to the script (you can ask on https://serverfault.com/ how to do this)
Well, first off you are mixing Simple HTML DOM and DOM Document. Just use one or the other. Since this is in the simple-html-dom tag start with this from the command line:
<?php
require_once("./simple_html_dom.php"); # simplehtmldom.sourceforge.net to use manual
$path="http://www.barringtonsports.com";
$html = file_get_html($path);
foreach ($html->find('a') as $anchor) {
$url = $anchor->href;
echo "Found link to " . $url . "\n";
# now see if the link is relative, absolute, or even on another site...
$checkhtml = file_get_html($url);
# now you can parse that link for stuff too.
}
?>
But really, that website has a search form, why not just send it a query instead and read the results?

WordPress Pagination not working with AJAX

I'm loading some posts though AJAX and my WordPress pagination is using the following function to calculate paging:
get_pagenum_link($paged - 1)
The issue is that the pagination is getting created through AJAX so it's making this link look like: http://localhost:1234/vendor_new/wp-admin/admin-ajax.php
However the actual URL that I'm trying to achieve is for this:
http://localhost:1234/vendor_new/display-vendor-results
Is there a way to use this function with AJAX and still get the correct URL for paging?
I can think of three options for you:
To write your own version of get_pagenum_link() that would allow you to specify the base URL
To overwrite the $_SERVER['REQUEST_URI'] variable while you call get_pagenum_link()
To call the paginate_links() function, return the whole pagination's HTML and then process that with JS to only take the prev/next links.
#1 Custom version of get_pagenum_link()
Pros: you would have to change a small amount of your current code - basically just change the name of the function you're calling and pass an extra argument.
Cons: if the function changes in the future(unlikely, but possible), you'd have to adjust your function as well.
I will only post the relevant code of the custom function - you can assume everything else can be left the way it's in the core version.
function my_get_pagenum_link( $pagenum = 1, $escape = true, $base = null ) {
global $wp_rewrite;
$pagenum = (int) $pagenum;
$request = $base ? remove_query_arg( 'paged', $base ) : remove_query_arg( 'paged' );
So in this case, we have one more argument that allows us to specify a base URL - it would be up to you to either hard-code the URL(not a good idea), or dynamically generate it. Here's how your code that handles the AJAX request would change:
my_get_pagenum_link( $paged - 1, true, 'http://localhost:1234/vendor_new/display-vendor-results' );
And that's about it for this solution.
#2 overwrite the $_SERVER['REQUEST_URI'] variable
Pros: Rather easy to implement, should be future-proof.
Cons: Might have side effects(in theory it shouldn't, but you never know); you might have to edit your JS code.
You can overwrite it with a value that you get on the back-end, or with a value that you pass with your AJAX request(so in your AJAX request, you can have a parameter for instance base that would be something like window.location.pathname + window.location.search). Difference is that in the second case, your JS would work from any page(if in the future you end-up having multiple locations use the same AJAX handler).
I will post the code that overwrites the variable and then restores it.
// Static base - making it dynamic is highly recommended
$base = '/vendor_new/display-vendor-results';
$orig_req_uri = $_SERVER['REQUEST_URI'];
// Overwrite the REQUEST_URI variable
$_SERVER['REQUEST_URI'] = $base;
// Get the pagination link
get_pagenum_link( $paged - 1 );
// Restore the original REQUEST_URI - in case anything else would resort on it
$_SERVER['REQUEST_URI'] = $orig_req_uri;
What happens here is that we simply override the REQUEST_URI variable with our own - this way we fool the add_query_arg function into thinking, that we're on the /vendor_new/display-vendor-results page and not on /wp-admin/admin-ajax.php
#3 Use paginate_links() and manipulate the HTML with JS
Pros: Can't really think of any at the moment.
Cons: You would have to adjust both your PHP and your JavaScript code.
Here is the idea: you use paginate_links() with it's arguments to create all of the pagination links(well - at least four of them - prev/next and first/last). Then you pass all of that HTML as an argument in your response(if you're using JSON - or as part of the response if you're just returning the HTML).
PHP code:
global $wp_rewrite, $wp_query;
// Again - hard coded, you should make it dynamic though
$base = trailingslashit( 'http://localhost:1234/vendor_new/display-vendor-results' ) . "{$wp_rewrite->pagination_base}/%#%/";
$html = '<div class="mypagination">' . paginate_links( array(
'base' => $base,
'format' => '?paged=%#%',
'current' => max( 1, $paged ),
'total' => $wp_query->max_num_pages,
'mid_size' => 0,
'end_size' => 1,
) ) . '</div>';
JS code(it's supposed to be inside of your AJAX success callback):
// the html variable is supposed to hold the AJAX response
// either just the pagination or the whole response
jQuery( html ).find('.mypagination > *:not(.page-numbers.next,.page-numbers.prev)').remove();
What happens here is that we find all elements that are inside the <div class="mypagination">, except the prev/next links and we remove them.
To wrap it up:
The easiest solution is probably #2, but if someone for some reason needs to know that the current page is admin-ajax.php while you are generating the links, then you might have an issue. The chances are that no one would even notice, since it would be your code that is running and any functions that could be attached to filters should also think that they are on the page you need(otherwise they might mess something up).
PS: If it was up to me, I was going to always use the paginate_links() function and display the page numbers on the front-end. I would then use the same function to generate the updated HTML in the AJAX handler.
This is actually hard to answer without specific details of what and how is being called. I bet you want to implement that in some kind of endless-sroll website, right?
Your best bet is to get via AJAX the paginated page itself, and grab the related markup.
Assume you have a post http://www.yourdomain.com/post-1/
I guess you want to grab the pagination of the next page, therefore you need something like this:
$( "#pagination" ).load( "http://www.yourdomain.com/post-1/page/2 #pagination" );
This can easily work with get_next_posts_link() instead of get_pagenum_link().
Now, in order for your AJAX call to be dynamic, you could something like:
$( "#pagination" ).load( $("#pagination a").attr('href') + " #pagination" );
This will grab the next page's link from your current page, and load its pagination markup in place of the old.
It's also doable with get_pagenum_link() however you'd need to change the $("#pagination a").attr('href') selector appropriately, in order to get the next page (since you'd have more than one a elements inside #pagination

Is there a Joomla function to generate the 'alias' field?

I'm writing my own component for Joomla 1.5. I'm trying to figure out how to generate an "alias" (friendly URL slug) for the content I add. In other words, if the title is "The article title", Joomla would use the-article-title by default (you can edit it if you like).
Is there a built-in Joomla function that will do this for me?
Line 123 of libraries/joomla/database/table/content.php implements JFilterOutput::stringURLSafe(). Pass in the string you want to make "alias friendly" and it will return what you need.
If you are trying to generate an alias for your created component it is very simple. Suppose you have click on save or apply button in your created component or suppose you want to make alias through your tile, then use this function:
$ailias=JFilterOutput::stringURLSafe($_POST['title']);
Now you can insert it into database.
It's simple PHP.
Here is the function from Joomla 1.5 source:
Notice, I have commented the two lines out. You can call the function like
$new_alias = stringURLSafe($your_title);
function stringURLSafe($string)
{
//remove any '-' from the string they will be used as concatonater
$str = str_replace('-', ' ', $string);
$str = str_replace('_', ' ', $string);
//$lang =& JFactory::getLanguage();
//$str = $lang->transliterate($str);
// remove any duplicate whitespace, and ensure all characters are alphanumeric
$str = preg_replace(array('/\s+/','/[^A-Za-z0-9\-]/'), array('-',''), $str);
// lowercase and trim
$str = trim(strtolower($str));
return $str;
}

Resources