Wordpress - shortcode for external permalink - wordpress

Hi folks maybe someone can help me. It does not work and I've already tried everything
This should be the shortcode:
[permalink url="http://www.domain.com/" linktext="My Link Text"]
And that the associated function:
function external_permalink( $atts ) {
$atts = shortcode_atts( array(
'linktext' => '',
), $atts, 'permalink' );
$url = get_permalink( array(
'url' => '',
'target' => 'self'
), $url, 'url' );
return '' . $atts['linktext'] . ''; }
add_shortcode('permalink', 'external_permalink');

I have no idea why you even have get_permalink because it shouldn't be there. This should work
function external_permalink($atts)
{
$atts = shortcode_atts(array(
'linktext' => '',
'url' => ''
), $atts);
return '' . $atts['linktext'] . '';
}
add_shortcode('permalink', 'external_permalink');

#Lee - Sorry, I thought it would be understandable what I mean.
#Kirk Beard - Maybe, but I like that better: [permalink url="http://www.domain.com/" linktext="My Link Text"]
as this: <div class="class1 class2">My Link Text</div>
#Igor Yavych - Wonderful! It is working. Many many thanks :)

Related

wp_localize_script is not accepting dynamic value

*Context
I am new to WordPress plugin development and I have just started developing one. Which is basically a blog slider plugin. The concept is very simple. The user can use shortcodes with parameters to determine which posts and how many posts to be shown. There is no admin settings page for changing the appearance of the slider though, but I'll work on that. The user have to use shortcode whenever the slider is needed.
The development part is also simple. I am checking the parameters that the user passes through the shortcode. And then a query runs and returns an array of posts and then displays the structure. Very simple.
*Problem
Now I am trying to make the plugin options more dynamic (via shortcode) i.e. the user can control whether the slider should auto-play or not, loop should be enabled or not, pause on hover, dots/nav hide or show etc. I am using owl carousel for this slider. So that means I have to change the attributes of the slider in JavaScript file.
The basic idea is to take the parameters from function's $atts array, and pass it to the JavaScript file. I know this can be accomplished using wp_localize_script, but I cannot figure out how.
Here is my code to make things more clear.
mainfile.php
add_shortcode( 'sp-slider', 'sp_slider_get_posts');
function sp_slider_get_posts( $atts ) {
$values = shortcode_atts( array(
'number' => '-1',
'category-id' => '', //DEFAULT VALUE null, WILL BE REPLACED ONCE USER DECLARES IN SHORTCODE
'category-name' => '',
'orderby' => '',
'order' => '',
'include-posts' => '',
'exclude-posts' => '',
'author-id' => '',
'author-name' => '',
'autoplay' => ''
), $atts );
if( !empty($values['number']) ||
!empty($values['category-id']) ||
!empty($values['category-name']) ||
!empty($values['orderby']) ||
!empty($values['order']) ||
!empty($values['include-posts']) ||
!empty($values['exclude-posts']) ||
!empty($values['author-id']) ||
!empty($values['author-name']) ||
!empty($values['autoplay'])) {
$args = array(
'numberposts' => $values['number'],
'cat' => $values['category-id'],
'category_name' => $values['category-name'],
'orderby' => $values['orderby'],
'order' => $values['order'],
'include' => $values['include-posts'],
'exclude' => $values['exclude-posts'],
'meta_key' => '',
'meta_value' => '',
'post_parent' => '',
'author' => $values['author-id'],
'author_name' => $values['author-name'],
'post_status' => 'publish',
'suppress_filters' => true,
'fields' => '',
);
$autoplay = $values['autoplay']; //GET AUTOPLAY VALUE. NO IDEA HOW TO USE IT. SO I TRIED THE FOLLOWING
// THE FOLLOWING FUNCTION HOLDS THE wp_localize_script FUNCTION, WHICH IS DECLARED AT THE END OF THIS CURRENT FUNCTION sp_slider_get_posts.
sp_carousel_settings($autoplay); //PASSING THE USER INPUT
$posts_array = get_posts( $args );
if( !empty( $posts_array ) ) {
$output = "<div class='sp-slider-wrapper'>";
$output .= '<div class="owl-carousel owl-theme">';
foreach( $posts_array as $post ) {
include( "includes/inc_slider_section.php"); // ALL THE SLIDER STRUCTURE IS IN DIFFERENT FILE WHICH IS INCLUDED HERE
}
$output .="</div>";
$output .="</div>";
}
return $output;
}
}
// HERE IS sp_carousel_settings() DECLARATION
function sp_carousel_settings( $autoplay ) {
$carousel_settings = array( 'autoplay' => $autoplay);
wp_localize_script( 'sp_main_js', 'carousel_settings', $carousel_settings );
}
add_action( 'wp_enqueue_scripts', 'sp_carousel_settings' );
mainjs.js
$(document).ready(function() {
...
...
var autoplay= '';
if(typeof carousel_settings !== 'undefined') {
autoplay = carousel_settings.autoplay;
}
else {
autoplay = false;
}
$('.owl-carousel').owlCarousel({
loop:true,
autoplay:autoplay,
autoplayTimeout:2000,
autoplayHoverPause:true,
...
...
}
})
This doesn't work. Here I would like to mention that, in add_action() function, if i put wp_footer instead of wp_enqueue_scripts, it adds the script to the footer of the page (I have checked it by viewing the source) but the autoplay value is null.
Another thing i would mention is that, in sp_carousel_settings() function, instead of passing the $autoplay variable, if I write any static value like this $carousel_settings = array( 'autoplay' => true);, it works.
*I tried echoing out $autoplay inside sp_carousel_settings() and it prints the value! But does not get to the js file.
*I tried checking the value of $autoplay and pass a hardcore sting inside wp_localize_script like
function sp_carousel_settings( $autoplay ) {
if( $autoplay == "true" ) {
echo "Inside!!!";
$carousel_settings = array( 'autoplay' => true);
}
else {
echo "Outside!!!";
$carousel_settings = array( 'autoplay' => false);
}
wp_localize_script( 'sp_main_js', 'carousel_settings', $carousel_settings );
}
add_action( 'wp_footer', 'sp_carousel_settings' );
Does not work. EVEN it prints out "Inside!!!" but does not pass true in autoplay. The value is always false.
*I have registered the js file in the beginning of the plugin, where the plugin activates and gets initialized. Like this
function sp_slider_include_css_js() {
...
...
wp_register_script('sp_main_js', plugins_url('assets/js/main.js',__FILE__));
wp_enqueue_script('sp_main_js');
...
...
}
add_action( 'wp_footer','sp_slider_include_css_js');
*I have searched internet for help but was unable to find. Any reference will be appreciated.
*I know that I might be using the function in an improper way. I am clueless (and new to this).
Have to do some changes like,
Step 1:
function sp_carousel_settings() {
wp_register_script( 'sp_main_js', 'you/file/path/here', array( 'jquery' ), '1.0', true);
}
add_action( 'wp_enqueue_scripts', 'sp_carousel_settings' );
Step 2:
add_shortcode( 'sp-slider', 'sp_slider_get_posts');
function sp_slider_get_posts( $atts ) {
.....
$carousel_settings = array( 'autoplay' => $autoplay);
wp_localize_script( 'sp_main_js', 'carousel_settings', $carousel_settings );
wp_enqueue_script( 'sp_main_js' );
......
}

WordPress : page not found with Relevanssi on some search pages on my search results

This is how I override the WordPress search page to implement better results thanks to Relevanssi:
global $wp_query;
$search_txt = get_query_var('s');
$args = array(
's' => $search_txt,
'post_type' => 'formations',
'posts_per_page' => 9,
'paged' => $wp_query->query_vars['paged'], // conserver le numéro de page de la requête initiale
);
// filtrer suivant la bonne taxonomy
if (isset($_GET['taxonomy'])) {
switch ($_GET['taxonomy']) {
case 'formation-diplomantes-cpf':
$ta = ['formation-diplomante', 'formation-eligible-au-cpf'];
$op = 'AND';
break;
case 'toute-formation':
break;
default:
$ta = $_GET['taxonomy'];
$op = 'IN';
}
if (isset($ta)) {
$tq = [[
'taxonomy' => 'type_form',
'field' => 'slug',
'terms' => $ta,
'operator' => $op,
]];// Tax Query
$args['tax_query'] = $tq;
}
}
$fq = new WP_Query();
$fq->parse_query( $args );
relevanssi_do_query($fq);
$any_formation = false;
$fdia = [];// Formations DIOGEN IDs Array
$fia = [];// Formations IDs Array
$i=0;
while ($fq->have_posts()) : $fq->the_post();
if ( 'formations' == get_post_type() ) {
$i++;
$fdia[get_the_ID()] = get_field('id_diogen', get_the_ID());
$fia[] = get_the_ID();
$any_formation = true;
}
endwhile;
?>
The results are paginated:
echo paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $fq->max_num_pages
) );
This works well in most cases:
https://cdma.happy-dev.fr/?taxonomy=toute-formation&s=design
https://cdma.happy-dev.fr/page/2/?taxonomy=toute-formation&s=design
https://cdma.happy-dev.fr/page/3/?taxonomy=toute-formation&s=design
It fails in others:
https://cdma.happy-dev.fr/?taxonomy=toute-formation&s=sophie
https://cdma.happy-dev.fr/page/2/?taxonomy=toute-formation&s=sophie
https://cdma.happy-dev.fr/page/3/?taxonomy=toute-formation&s=sophie
I ended up understanding that pagination of my formations was not working when I didn’t have enough actualites. That is, say I have a query that brings 10 formations, and 20 actualites: everything works as expected. The opposite fails however.
This is how I rewrite URLs regarding actualites:
function custom_rewrite_rules( $wp_rewrite ) {
$wp_rewrite->rules = array(
'actualite/page/?([0-9]{1,})/?$' => $wp_rewrite->index . '?pagename=actualite&paged=' . $wp_rewrite->preg_index( 1 ),
) + $wp_rewrite->rules;
}
add_action( 'generate_rewrite_rules', 'custom_rewrite_rules' );
I tried to had a prefix to the search URL thinking that could play a role, but to no avail.
I also tried adding a custom rewrite rule for the search page, but it is not having any impact. I still get 404s.
I spent hours digging every possible direction but to no avail.
Any suggestion is most welcome.
I don’t see why both pagination of formations and actualites are related.
The polylang plugin was causing the trouble. Deactivating it solved the problem.

How to properly save a WordPress option containing HTML code?

Here's a screenshot of what the problem looks like:
And the HTML of that part of the WordPress options page looks like this:
So, in the WordPress admin area, I entered a piece of HTML code (to have a clickable link as the output on the frontend).
This was the code I had entered into that text input field on the backend:
<a title="Website Design London" href="../../website-design/">Website Design</a>
And while on the frontend that link is displaying OK, I'm seeing this mess (see screenshot) on the backend.
As far as I can tell the relevant PHP code is this:
$this->text(
'workdone',
esc_html__( 'Work done', 'mytheme' )
);
So, what is the proper way to save an option that contains HTML code?
And how can I fix the mess shown on the screenshot?
I had the same issue, and this code is working for me:
// render service label
public function render_service_label() {
$value = get_option( 'wbk_service_label', '' );
$value = htmlspecialchars( $value );
$html = '<input type="text" id="wbk_service_label" name="wbk_service_label" value="'.$value.'" >';
$html .= '<p class="description">' . __( 'Service label', 'wbk' ) . '</p>';
echo $html;
}
// validate service label
public function validate_service_label( $input ) {
$allowed_tags = array(
//formatting
'strong' => array(),
'em' => array(),
'b' => array(),
'i' => array(),
'br' => array(),
//links
'a' => array(
'href' => array(),
'class' => array()
),
//links
'p' => array(
'class' => array()
)
);
$input = wp_kses( $input, $allowed_tags );
return $input;
}
So, in the dashboard options page I use htmlspecialchars function
In frontend page I use like this:
$label = get_option( 'wbk_service_label', __( 'Select service', 'wbk' ) );

change pagination link in WordPress

I am getting pagination links like -> /page/3. But i would like to change this "page" to "news". Is it possible?
Thank you!
echo paginate_links( array(
'base' => str_replace( $big2, '%#%', esc_url( get_pagenum_link( $big2 ) ) ),
'format' => '?paged1=%#%',
'current' => max( 1, get_query_var('paged1') ),
'total' => $news->max_num_pages,
'mid_size' => 0,
'type' => 'plain',
'end_size'=>0,
'prev_text' => '<IEPREKŠĒJĀ LAPA',
'next_text' => 'NĀKOŠĀ LAPA>'
) );
function my_custom_pagination_base() {
global $wp_rewrite;
$wp_rewrite->pagination_base = 'p'; //where new-slug is the slug you want to use
$wp_rewrite->flush_rules();
}
add_action('init', 'my_custom_pagination_base', 1);
You can change pagination base using below code
<?php
add_action( 'init', 'my_custom_page_word' );
function my_custom_page_word() {
global $wp_rewrite; // Get the global wordpress rewrite-rules/settings
// Change the base pagination property which sets the wordpress pagination slug.
$wp_rewrite->pagination_base = "news"; //where new-slug is the slug you want to use ;)
}
?>
For reference you can refer below link
https://wordpress.stackexchange.com/questions/57070/change-the-page-slug-in-pagination
To remove page or whatever your base is set to for your pagination do the following.
First add the following to functions.php. This function will rewrite our base pagination prefix to and empty string.
function my_custom_pagination_base() {
global $wp_rewrite;
$wp_rewrite->pagination_base = '';
$wp_rewrite->flush_rules();
}
add_action('init', 'my_custom_pagination_base', 1);
Second we add the our paginate_links() function to our archives page. with the following arguments. Make sure base is not set, or it will mess up our rewrite function.
echo paginate_links(array(
'format' => '\\%#%/',
'current' => max( 1, get_query_var('paged') ),
'total' => $wp_query->max_num_pages
));
Set your current and total args to whatever you need them to be.
Your archive pagination url should look like www.site.com/some-category/2/ when you go to page 2

Contact Form 7 and Custom post type

I want to use contact form 7 in Wordpress to build a order Form. I want the content of the order Form to be populated with content from a custom post type "trade Show Material" - The post type contains the fields "name" "number" "description" "photo" . The idea will be that each piece can be selected from the form . Can anyone offer the general direction for this? Should I perhaps be using another plugin entirely?
Maybe you can use the wpcf7_form_tag filter hook for this.
If you want to use a custom post type as the options of a dropdown (select) you can add something like the example below in your functions.php:
function dynamic_field_values ( $tag, $unused ) {
if ( $tag['name'] != 'your-field-name' )
return $tag;
$args = array (
'numberposts' => -1,
'post_type' => 'your-custom-post-type',
'orderby' => 'title',
'order' => 'ASC',
);
$custom_posts = get_posts($args);
if ( ! $custom_posts )
return $tag;
foreach ( $custom_posts as $custom_post ) {
$tag['raw_values'][] = $custom_post->post_title;
$tag['values'][] = $custom_post->post_title;
$tag['labels'][] = $custom_post->post_title;
}
return $tag;
}
add_filter( 'wpcf7_form_tag', 'dynamic_field_values', 10, 2);
In your form you can add the field:
[select* your-field-name include_blank]
In the example above the post_title is used in the options of the dropdown. You can add your own fields here (name, number, description, photo).
I do no think the wpcf7_form_tag works in the same way as vicente showed in his great answer before. It may have changed since 2015.
If you read here it explains how you need to use the wpcf7_form_tag: https://contactform7.com/2015/01/10/adding-a-custom-form-tag/
With that in mind along with this other post from Contact Form 7: https://contactform7.com/2015/02/27/using-values-from-a-form-tag/#more-13351
I came up with this code to create a custom dropdown list for a custom post type that I have.
add_action( 'wpcf7_init', 'custom_add_form_tag_customlist' );
function custom_add_form_tag_customlist() {
wpcf7_add_form_tag( array( 'customlist', 'customlist*' ),
'custom_customlist_form_tag_handler', true );
}
function custom_customlist_form_tag_handler( $tag ) {
$tag = new WPCF7_FormTag( $tag );
if ( empty( $tag->name ) ) {
return '';
}
$customlist = '';
$query = new WP_Query(array(
'post_type' => 'CUSTOM POST TYPE HERE',
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'ASC',
));
while ($query->have_posts()) {
$query->the_post();
$post_title = get_the_title();
$customlist .= sprintf( '<option value="%1$s">%2$s</option>',
esc_html( $post_title ), esc_html( $post_title ) );
}
wp_reset_query();
$customlist = sprintf(
'<select name="%1$s" id="%2$s">%3$s</select>', $tag->name,
$tag->name . '-options',
$customlist );
return $customlist;
}
Then you use the tag in contact form 7 like this.
[customlist your-field-name]
Hopefully this helps someone else who was looking for a way to do this like I was.
You could alter it to get any information you need from the custom post type.
It does not have any validation though.
Clyde Thomas code still works nice, thanks !
In my case I need the data from a plugin instead of a post so I've modified the code removing the WP_query and the while
global $wpdb;
$result = $wpdb->get_results("SELECT title FROM wp_asl_stores ORDER BY title ASC ");
foreach($result as $row) {
$customlist .= sprintf( '<option value="%1$s">%2$s</option>',
esc_html( $row->title ), esc_html( $row->title ) );
}

Resources