INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Modify Date Format to German
I basically need to change the date format to german date format all over the WordPress site and I succeed it by changing the date time settings from the WordPress admin panel.
> **Settings » General** :
>
> **Date Format** \- Custom : j. F Y
>
> eg : 5. July 2016
However I need to change the month names to german as well.
> eg : 5. Juli 2016
How should I do that ? | I have added the following code to child theme function and it works,
add_filter('the_time', 'modify_date_format');
function modify_date_format(){
$month_names = array(1=>'Januar','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember');
return get_the_time('j').'. '.$month_names[get_the_time('n')].' '.get_the_time('Y');
}
But I'm not sure this is the correct way to do it. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "date, options, date time"
} |
Wordpress monthly upload directory owner set to root
This is a weird one.
Wordpress by default stores uploaded media in monthly sub-directories of the uploads directory. Eg wp-content/uploads/2016/07/
On one of my sites, this directory's owner gets set to "root:root", which means that nothing can be uploaded to the directory via the web server.
Any ideas what might cause this behaviour? I can imagine a cron script creating this behaviour, but I don't see how Wordpress itself should be able to create a directory owned by root. | I've had the same problem, and in my case it was the Wordpress cronjob. I was calling the wp-cron.php as a root cron job, and this script also generates the monthly upload folder.
If you call wp-cron.php via cronjob you need to do this as the web server user (or i.e. in Plesk the site user and group psacln). The owner of the created monthly folder is always the user the wp-cron.php is called from. | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 5,
"tags": "uploads, permissions, linux"
} |
Load a Header in wordpress
I'm trying to added upload header in Wordpress but not upload the image but it print out the link of the header. How do I fix the problem the him have with wordpress.
<?php if ( get_header_image() != '' ) {
$banner = 'style="background-image:url('. header_image() .');"';
} else {
$banner = '';
} ?>
<main class="site-header" <?php echo $banner; ?> role='banner'> | You're really close - `get_header_image()` _returns_ the URL of the image, whereas `header_image()` _echo's_ out the URL.
Because you're setting your style tag in a variable and then echo'ing that, you need to use the function that _returns_ the header image URL - so, like this:
$banner = 'style="background-image:url('. get_header_image() .');"';
Using `header_image()` will, as you found, echo out the URL directly, before you're actually wanting to do so in your case.
Incidentally, a lot of WordPress functions follow this same naming scheme. Generally, a function starting with `get_` will return the value, whereas a function starting with `the_`, or sometimes omitting it as in this case, will echo the value out. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "php, functions"
} |
Add Content to Page without shortcodes
The site I'm working on has a couple of pages that needs to be filled with different content elements like text image combinations, sliders, lists of content, etc. The client would need to re-order these content blocks, add new ones and so forth. Every content block would be piece of content (post or custom post type) or a list of content.
From what I understand I have 2 options:
1. Use an complex plugin to drag and drop predefined content
2. Use shortcodes
From a developing standpoint I would rather not leave all the logic to a third party plugin. It seems I would lose some of the control over the templating?
But shortcodes don't seem like an acceptable solution for any customer, really, because they are too technical.
Any suggestions? Is there a best practice? | I evaluated the different options and went with a plugin "Page Builder". While the technical aspects are not great (e.g. data persisting: all content gets serialized) is was the only option to give me enough flexibility and enough comfort so that the customer could make changes to the structure of each page.
Migrating from dev to stage to live was also a pain due to the serializing and only possible with yet another plugin (duplicator).
Thanks everyone for the input! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 5,
"tags": "custom post types, shortcode, templates, page template, custom content"
} |
Show get_sub_field value if it exists
I'm using Advanced Custom Fields in a WP build. I have the following:
`<h1 class="title"><?php echo get_sub_field('title'); ?></h1>`
How do I only show this if someone's filled in the title field? | You need to make the whole line conditional, like this:
$sub_field_title = get_sub_field('title');
if (!empty($sub_field_title)) {
echo '<h1 class="title">' . $sub_field_title . '</h1>';
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, advanced custom fields"
} |
Exclude filter on front page
I am using this code in `functions.php` to append a button for link to a post.
function new_excerpt_more($more) {
global $post;
return '<a class="excerpt-readmore" href="'. get_permalink($post->ID) . '">Read more</a>';
}
add_filter('excerpt_more', 'new_excerpt_more');
In `front-page.php` I have `get_template_part('content-ctp');` and in that file I have
$args = array(
'post_type' => 'radovi'
);
$ctp = new WP_Query($args);
...
the_excerpt();
Is there a way to not have the read-more button only for this specific loop? I don't think I can check with `if(!is_front_page())` on filter since I also have 2 more loops on front page where I need that button. Any suggestions on how to do it properly the Wordpress way? | You can just remove the filter before calling `the_excerpt` and then add it back afterwards...
remove_filter('excerpt_more','new_excerpt_more');
the_excerpt();
add_filter('excerpt_more', 'new_excerpt_more'); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "loop, filters, excerpt, read more"
} |
Custom page template for multiple pages
A site I'm currently working on has a page structure like this
About Us
|
|_People
| |
| _ Person 1
| _ Person 2
| _ Person 3
|... etc ...
Every 'Person' page is a separate page, but they all have the same structure using a few ACF fields to display a person's bio, photo etc.
I know how to create a custom page template for one specific page, i.e. page- _slug_.php, but I want to use one page template for all of those subpages.
What would be the easiest way to accomplish this? | You can always make use of the `page_template` filter to tell WordPress to use a specific page template for all child pages of a certain parent. It is as easy as creating a special page template, lets call it `page-wpse-person.php`.
Now it is as easy as including that template whenever a child page of `people` is being viewed. For the sake of example, lets say the page ID of `people` is `10`
add_filter( 'page_template', function ( $template ) use ( &$post )
{
// Check if we have page which is a child of people, ID 10
if ( 10 !== $post->post_parent )
return $template;
// This is a person page, child of people, try to locate our custom page
$locate_template = locate_template( 'page-wpse-person.php' );
// Check if our template was found, if not, bail
if ( !$locate_template )
return $template;
return $locate_template;
}); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "pages, page template, child pages"
} |
Use default image as var
I would like to use a default image if there is no thumbnail. The image needs to be output as $image. But I can't work out how to use the image path to the default image.
if ($locimage) {
$image = $locimage;
$image = $image[0];
} else {
$image = "'. get_bloginfo('template_directory') .'/images/images/default.png .";
} | This is mostly a PHP general question about concatenating a function's returned value with a (or many) string(s).
The get_bloginfo function **returns** a string instead of **echoing** it directly.
Thus you start off with:
// First param value: stylesheet_directory
// Using "template_url" also works unless you are using a child theme
// In that case, "template_url" will not return your child theme's directory path
$image = get_bloginfo('stylesheet_directory');
If you want to manually add a string to that value, you concatenate the get_bloginfo() returned value (of type string) by adding a dot (.) followed by either single or double quotes, like the following:
$image = get_bloginfo('stylesheet_directory') .'/images/images/default.png'; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "images, post thumbnails"
} |
What is the best practice for restricting a section to logged in users?
As a newbie, I've had a hard time finding a good starting point. I believe my case is fairly common and maybe this question has been answered comprehensively elsewhere.
I am creating a simple site for a non-profit agency. The public front end has the basic About/Blog/Donate/Contact pages.
The (non-paid) members-only side will have a blog, events calendar, forum, and a table displaying meta info for all users.
I am searching for the best starting point to implement this. I don't know whether to build a members.domain.org subdomain, or to simply add code to restricted pages that would redirect non-logged-in users.
Thank you in advance for any insight. My searches continue to lead me into a jungle of WordPress plugins and I'm feeling lost. | I think the answer is "it depends" -- on how flexible and/or "slick" you want the solution to be. The quickest/easiest thing to do would be to create a custom post type (there are tried/true plugins out there that can help establish this) -- and then in your theme functions.php (or in a very simple plugin), put in logic that redirects non-logged in users to a page of your choice, if the current post is of that type:
function guest_restrict () {
if ( !is_user_logged_in() && "restricted_post" == get_post_type( get_the_ID() ) )
wp_redirect( ' );
}
add_action('template_redirect','guest_restrict');
A "full blown" solution would be to bolt in a membership system (plugin) but that is a much bigger deal. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, security, subdomains, membership"
} |
How to hide post content/meta from everyone except the post author and admin
I'm trying to start myself off here but I can't get my head around it... How can I hide an author's post content/meta from everyone except the post author and admin? This is my scenario... Schools and teachers publish their own custom posts Schools/Admin can see all teachers posts but only the teacher who published the post can see their post, other teachers can't see other teacher's posts. | You can try below code -
<?php
global $current_user;
if ((is_user_logged_in() && $current_user->ID == $post->post_author) || current_user_can( 'manage_options' )) {
echo 'my post';
}
?>
Check below link also-
< | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "wp query, user roles"
} |
Custom metabox for custom page template
I have created custom page template. Now I have to make it configurable, however since I am using more than one template in my theme I would like to make sure that configuration will be available only when the user chooses this template for a page. Is there an option to do so?
`add_meta_box` accepts different `$post_type`, so the closest I can get is to add metabox to all pages, which I would like to avoid. | <?
// Check:
// 1. If you are editing post, CPT, or page
// 2. If post type IS NOT SET
if( 'post.php' == basename($_SERVER['REQUEST_URI'], '?' . $_SERVER['QUERY_STRING']) && !isset($_GET['post_type']) ) {
// get post ID
$postid = $_GET['post'];
// check the template file name
if ('my_template.php' == get_page_template_slug($postid) ) {
// add your metabox here
add_action( 'add_meta_boxes', 'my_metabox' );
}
}
I don't remember why I was checking post type, not post ID, but you can change
!isset($_GET['post_type'])
to check if post ID is set:
isset($_GET['post'])
**Note** : meta box will be available only after you save your post (page) using appropriate template. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "theme development, metabox, page template"
} |
Bring a post to the top of the query if it's in a certain category?
I'm looking for a way to bring a post if it's in a certain category to the front (or top) of the list. The category is called 'first'. I don't think `orderby` supports category so what other options do I have? Should I create another query inside the first query?
Thanks, | You will have to use 2 queries, where in the first loop you should use:
$args = array(
"post_type" => "post",
"post_status" => "publish",
"orderby" => "date",
"order" => "DESC",
"posts_per_page" => 20,
'post__in' => cat,
);
(The Query)
And in the second:
$args = array(
"post_type" => "post",
"post_status" => "publish",
"orderby" => "date",
"order" => "DESC",
"posts_per_page" => 20,
'post__not_in' => cat,
);
(The Query)
This should work because the first loop will take only the posts from `cat` and the second loop all others, and the first loop will always stay on top, Altought I don't know if you won't have a problem with the paginations that way, you should also ensure that you reset the post data with `wp_reset_query();` for example. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query, query"
} |
How to show metabox just in post.php in admin?
I want to show my metabox in `post.php?action=edit` not in `post-new.php`. How can I do that? | One simple solution is to check with the query string from the request:
if ( !empty( $_REQUEST['action'] ) && "edit" == $_REQUEST['action'] ) {
/* proceed */
}
But it is also a good practice to use @mmm's suggestion since you are working with meta boxes where you have the `$post` object in use. When composing a new post, there's an automatically created post with a status of `auto-draft`, so let's proceed the meta box coding when the status is something other than `auto-draft`, say `publish` for instance:
if ( !empty( ( $status = get_post_status( $post->ID ) ) ) && "auto-draft" !== $status ) {
/* proceed */
}
Glad that helped. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, metabox"
} |
Group posts by year in loop
How can I separate posts by year in archive page for Custom Post Type?
while ( have_posts() ) : the_post();
the_title();
the_post_thumbnail('thumb');
endwhile;
The end result would look something like this:
2016
- Title1
- Title2
- Title3
- Title4
2015
- Title1
- Title2
- Title3
- Title4
etc. | This little snippet could help you.
$years = array();
if( have_posts() ) {
while( have_posts() ) {
the_post();
$year = get_the_date( 'Y' );
if ( ! isset( $years[ $year ] ) ) $years[ $year ] = array();
$years[ $year ][] = array( 'title' => get_the_title(), 'permalink' => get_the_permalink() );
}
}
This code gets all posts (in the current loop), gets the year of each post, pushes each post title and permalink to its year array. | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 1,
"tags": "posts, wp query, loop"
} |
Wordpress restriction to the whole website
I am looking for idea or some plugin, that restricts all the wordpress website and you can unlock it only if you have a credentials. The idea is: when you write the url of the website to open a login form (which is not from the wordpress, it will be custom form with external API) and when you successfully add your username and password it will unlock the whole wordpress website. Any ideas how to make it or some plugin? | This can be done as concisely as follows (in your theme `functions.php` or a plugin):
function wpse_231970_lockdown() {
if ( ! is_user_logged_in() ) {
global $wp;
/**
* Redirect to login page with redirect back to current request.
*/
wp_redirect( wp_login_url( $wp->request ) );
exit;
}
}
add_action( 'template_redirect', 'wpse_231970_lockdown' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "plugins"
} |
What is the best practice for renaming Wordpress media files?
Occasionally I change the name of a media file in Wordpress, but the filename (see screenshot) does not change in the process. I see a handful of plugins online that purport to change this. I'm just wondering if there are other non-plugins methods to carry this out.
Is one (the only?) option to directly edit my database? | As Rarst has explained, you can't really directly edit your database, or you'll risk killing the serialized data.
Your options are thus to:
* delete the file and re-upload it with its new name (obviously has the downside of having to reinsert it everywhere it was being used), or to
* use one of the media renaming / replacing plugins, which through one method or another take care of updating all links to the file.
If your concern is having _yet another plugin_ installed, you can always sit it there deactivated and just activate it when you need it. I use this for a variety of media "tool" plugins, because I only really need them once in a while. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 5,
"tags": "media"
} |
Is there a way to list posts of only a certain category
I want to add a new menu point to post that shows posts of a certain category. Adding a new page is easy if it is just a new post type. But I want to only show posts with a specific category and when updating posts make sure the category is checked.
IS there no way of doing this? I was hoping for some simple functon, like the way register_post_type() does it. As there doesn't seem to be, does anyone give me any tips about how to do this? Is it even possible? Or should I just use a custom post type? | You can filter the posts list by appending `?category_name=xx` to the admin posts list URL, and you can add a submenu page with that URL as the target via `add_submenu_page`:
add_action( 'admin_menu', 'wpd_admin_menu_item' );
function wpd_admin_menu_item(){
add_submenu_page(
'edit.php',
'Page title',
'Menu item title',
'edit_posts',
'edit.php?category_name=somecat'
);
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "custom post types, categories, wp list table"
} |
Htaccess remove dates from root site but not from subdomain
I have a site and a subdomain, so for example let's say:
In my hosting the subdomain store is actually a folder on the root site.
ON the main site, I want to do a permalink rewrite to remove the dates from the permalink, but NOT on the store.mysite subdomain. I used Yoast's redirect tool to get the htaccess code, which is:
RedirectMatch 301 ^/([0-9]{4})/([0-9]{2})/([0-9]{2})/(.*)$
This works on the root, but it also applies this to the subdomain. I tried using this htaccess rule only work on the root site:
RewriteCond %{HTTP_HOST} ^www\.example\.com$
RewriteRule ^([0-9]{4})\/([0-9]{2})\/([0-9]{2})\/(.*) \/$4 [R=301,NC,L]
But now the redirect doesn't even work at all. I've searched everything I can find but cannot find a specific use case like this. Any experts on htaccess care to give me a hand and let me know what's wrong with my code? Thanks! | I figured out my own answer, so am posting it here so if someone else runs into the same problem, they can see what I did.
The issue for me was that the base Wordpress redirect code:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
was at the top of the htaccess file, so it was firing first before any of the redirects were. When I moved that to the bottom, the redirects began working again.
So if you are going to use the rewritecond and rewriterule, they need to go BEFORE the Wordpress rewritecond and rewriterule. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "htaccess"
} |
What are nulled themes?
In WordPress there is a concept of _" Nulled Themes"_. I searched information about it (on Google) and found some people say it is hacked and others say it is not. I ran the _" iThemes Security"_ software over it and everything works without errors.
The Question is:
> Are _" Nulled Themes"_ hacked or not secured?
>
> Is "Themekiller" (` a secure website to download a _" Nulled Theme"_? | Nulled theme basically mean cracked/hacked. The distributors of such themes often hide popups/ads inside to earn money, which you can't see until a user complains about it or you check the website on google speed test for example where you see the image of the website, they aren't secure at all, and it is not worth using them.
Expected behavior of nulled themes and plugins: Hidden ads/popups/links which benefit the distributor, bad performance in most of the cases, sometimes malware and shells are being injected in the theme, in order to track the information.
Saving 40$ for a theme will waste your time in debugging the nulled theme, living in fear if the developer will take legal actions against you for it, lack of updates, lack of support for it and other features which are theme related and last but not least you support a bad industry and split on many hours of developing a theme.
Simply don't! : ) | stackexchange-wordpress | {
"answer_score": 15,
"question_score": 3,
"tags": "themes, security"
} |
Force WordPress, themes & plugins into using defined sizes
Many users do not compress or resize their images before uploading them into a post, so source images can often be a lot larger than the settings in /wp-admin/options-media.php.
Many theme and plugin authors do not respect the default settings in /wp-admin/options-media.php and often do not create custom sizes for things like gallery sliders.
The result is huge-ass images on pages and a slower internet.
WordPress provides 3 default image sizes and allows theme authors to create custom sizes as needed.
Does anyone know how to force WordPress, themes and plugins into using defined sizes in /wp-admin/options-media.php and/ or custom sizes created with add_image_size?
I've seen a few posts on here about deleting original source files, but it seems to me that leaving the original images on the server is nice a reference and fallback for re-cutting with Regenerate Thumbnails later if you need to change themes at a later date. | Imagify will resize images on upload, keep the original, AND optimize all thumbnail sizes at upload time. Best all-in-one solution I've found. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "media, images"
} |
How to get list of all hooks of current theme / plugin?
I want to get the list of all available hooks from active theme / from a specific plugin.
I was tried to get it from global variables `$wp_actions & $wp_filter` But, They are showing all registered hooks.
E.g.
global $wp_actions, $wp_filter;
echo '<pre>';
print_r($wp_filter);
E.g. If theme or plugin register the action in `after_setup_theme` then it'll list in `[after_setup_theme]` key from `global $wp_filter`.
I was tried one of the best plugin `Simply Show Hooks`. But, It'll also, show all the registered hooks.
Is there any way to get the specific hooks from theme / plugin? | As of 2016-09-25, there is no ideal solution.
The WP-Parser does the job, but you need to set up a special WP site to run it. WooCommerce's `Hook-docs` is something much simpler, and can be easily tweaked.
I just wrote a long comment on the topic here:
< | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 4,
"tags": "filters, hooks, actions"
} |
Can I save post meta programatically without setting metaboxes?
I want to know if is it required to have metaboxes set to save post meta into a custom post type.
I have a couple of pages where I save metadata into a post programatically, using `add_post_meta`, but I wanted to know if I can save data that is not set using `add_meta_box`.
Is it possible? What kind of considerations I should have about this? | You should always use `update_post_meta()` function because if the term doesn't exist it will make a call to the `add_post_meta()` automatically.
The same goes for `update_user_meta()`.
Example if you want to add the meta "City" but you don't have it in the db you simply make a `update_post_meta($city)` and in `$city` you need the `post_id` and the `new value for city`. Like that :
$city = array(
'post_id' => $post_id,
'city' => 'Melbourne'
);
For more information refer to : codex.wordpress.org/Function_Reference/update_post_meta | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom field, metabox, post meta"
} |
Prioritize visible content - Page speed issue on Google insights
I'm new to wordpress and i tried to speed up the site, but i got some error please see the image. I used w3 total cache,autoptimize and Above The Fold Optimization plugins. But still site is slow on mobile version. Please suggest me. Thx adv
;
if ( in_array( 'subscriber', (array) $user->roles ) ) {
// The current user has the subscriber role, show the form
comment_form( array(
'title_reply_before' => '<h2 id="reply-title" class="comment-reply-title">',
'title_reply_after' => '</h2>',
) );
}
This way, only those users with the subscriber role will see the comments form. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "comments"
} |
Shortcode: How to add custom posts?
I am having problems with post__in shortcode atts. It does not show anything. I think the problem is that **post__in must be an array but the shortcode ID returns string**.
function courses_shortcode($atts) {
extract(shortcode_atts( array(
'limit' => 16,
'id' => array(592, 862, 418, 491, 1227, 1015, 847, 738, 541, 1186, 664, 695, 785),
), $atts ));
$q_courses = new WP_Query( array(
'post_type' => array('course'),
'posts_per_page' => $limit,
'post__in' => $id,
'orderby' => 'post__in',
));
add_shortcode('video-course', 'courses_shortcode');
The problem is that if I do [video-course limit=8 id="418, 1186"] does not show anything. Limit is working but the **ID is not**. | Correct. post__in requires an array but the id parameter in [video-course limit=8 id="418, 1186"] is passed in as a string, so in your shortcode, you would have to parse it into an array in order to use it:
if ( !is_array($id) ) {
// If $id is not an array (not your default value in your example)
// then simultaneously parse it into an array and trim white space:
$id = array_map('trim', explode(',', $id));
}
Then you can use:
'post__in' => $id | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, shortcode"
} |
Script Localization doesn't work
I don't get how script localization works in wordpress. I created an associative array in php:
$translations = array(
'value1' =>'This is first value',
'value2' =>'This is second value'
);
I created simple javascript file where I want to use this array:
jQuery(document).ready(function($){
alert(translations);
});
Then I try to enqueue and localize this javascript file in my plugin like this:
function kvkoolitus_load_comment_validation(){
wp_enqueue_script( 'simple-js', plugin_dir_url( __FILE__ ) . 'js/jquery.simple.js', array('jquery'), '', true );
wp_localize_script( 'simple-js', 'translations', $translations );
}
add_action( 'wp_enqueue_scripts', 'kvkoolitus_load_comment_validation' );
But when I load a page with this javascript file, alert tells me that 'translations' object is null.
What did I miss? | Copying from the answer here regarding variable scope
Variables inside a function are only available inside that function.
Variables outside of functions are available anywhere outside of functions,
but not inside any function.
Because of that, you need to add your `$translations` array within the `kvkoolitus_load_comment_validation` function, like
function kvkoolitus_load_comment_validation(){
$translations = array(
'value1' =>'This is first value',
'value2' =>'This is second value'
);
wp_enqueue_script( 'simple-js', plugin_dir_url( __FILE__ ) . 'js/jquery.simple.js', array('jquery'), '', true );
wp_localize_script( 'simple-js', 'translations', $translations );
}
add_action( 'wp_enqueue_scripts', 'kvkoolitus_load_comment_validation' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "javascript, wp enqueue script, array, localization, wp localize script"
} |
On login redirect to different homepage if user is using a mobile
I have a responsive website which is accessed via login only. When the user logs in they are taken to 'Page 1' (and it is set as the front page).
I would like mobile users to be redirected to 'Page 2' on login. I've found a function which checks if they're using a mobile but it won't let me access 'Page 1' as it redirects back to 'Page 2'.
This is the function:
function so16165211_mobile_home_redirect(){
if( wp_is_mobile() && is_front_page() ){
wp_redirect( ' );
exit;
}
}
add_action( 'template_redirect', 'so16165211_mobile_home_redirect' );
Is it possible to modify this so it only redirects the mobile user once they've logged in as I'd still like them to access 'Page 1'. | You can use login_redirect hook. For example:
add_filter('login_redirect', function($to, $request, $user)
{
if ( wp_is_mobile() ) $to = admin_url('profile.php');
return $to;
}, PHP_INT_MAX, 3); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "redirect, mobile"
} |
Check if comment was successfully submited
Is there a way to check that comment was successfully submitted? I want to display some text or hide a comment form for example if comment was succesfully submitted. | Wordpress adds hashtag to URL if comment was successfully submitted. The easiest way to hide comment form or display some info is to check if hash exists with Javascript.
hash = window.location.hash;
if(hash){
$('#commentform').hide();
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "comments, publish, comment form"
} |
Query Shortcode from a multisite to appear on a different site?
So, I have a map shortcode on a page template that is used like this:
echo do_shortcode('[bgmp-map]');
The shortcode works great, but I was hoping to query the site that the shortcode displays, and display that on ANOTHER site within my multi site... is that possible? I want to do this because it would be so much easier to bring that information in and manage it only in one place. | I actually solved this... here's what you need to do if anyone needs to do something similar:
SO, you can't really query a site, but you can query pages on sites... so what I did was make a new page on the site where everything looked good, embed the shortcode, query that page and the content only on the other site. You NEED to have the site switch to that one to retrieve it though on the other multisite. You can look that up in the wp admin under "sites" to see the site ids.
Example:
<?php switch_to_blog(2); ?>
//changes to the site you want to query
<? $the_query = new WP_Query( 'page_id=229' );
while ( $the_query->have_posts() ) :
$the_query->the_post();
the_content();
endwhile;
wp_reset_postdata();
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, php, multisite, shortcode"
} |
Page template compatibility with different themes
I'm back to WordPress development after a long time away from it, and I'm currently writing a plugin for a client that I might find some use to some others. One part of the plugin includes a page template where users have to go.
Now I could style the said page template directly for the client, but it kind of kills the "reusability" factor of it.
I guess my qustion then is: is there a way to ensure a page template have maximum compatibility over all, or no, let's say a maximum, of the themes out there? My guess is no, since all theme developers can do pretty much whatever they can, but maybe one of your have a different opinion.
How would you ensure that a page template is as compatible as possible to a maximum of theme? | This is not possible at all. There aren't even duplication between page templates between the bundled themes.
There is no way for you to know or to predict functions, outlay or markup in any template. IMHO, because of this, templates should always reside within a theme and not in a plugin. Afterall, templates are theme specific and not compatibable cross themes.
Even if it was possible, I would really think that it would be an unmaintainable mess. Introducing new templates in a theme is easy, and it keeps thing maintainable without effort.
As @Milo suggested, there are a couple of filters which you can use to target what is being displayed on a page which includes
* `the_post`
* `the_posts`
* `loop_start` and `loop_end`
* post filters like `the_content` and `the_title`.
There is also the possibility of using shortcodes which is meant for something like what you want to do | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, templates, page template"
} |
Why do I have blury images in Wordpress
It seems Wordpress is doing an exceptionally bad job when it comes to re-sizing my images.
In the media options I have set my image sizes to my liking. Most notably 857px wide for the medium thumbs, and set the quality to 100, as well as turned on sharpening.
I have set the following in the functions.php
add_filter( 'jpeg_quality', create_function( '', 'return 100;' ) );
Sadly this has little to no affect at all on the quality of the images produced in Wordpress.
, how are you confident managing _any_ content via admin?
This might be a sign that you haven't fully figured out how your content workflows meant to be handled in WordPress, be it permissions, backups, or something else.
Also your "empty pages" approach seems fragile. The idea has been explored here and there in the past, for example as Static Templates, but I wouldn't say it is mainstream in WP development. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "pages, page template, static website"
} |
Send email messages after comment was submitted
I need to send 2 email messages: if comment was submitted and when comment was approved. Without any plugin of course. How can I do this? | For comment approved, you can review this question
Approve comment hook?
For comment submitted, you can hook into the `comment_post` hook, like
function show_message_function( $comment_ID, $comment_approved ) {
if( 0 === $comment_approved ){
//function logic goes here
}
}
add_action( 'comment_post', 'show_message_function', 10, 2 );
Code copied from < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, comments, email, comment form, notifications"
} |
How do I make search results include ONLY pages, no posts?
I'm trying to return only pages in search results.
This is working:
`/?s=term&post_type=post`
It returns only posts, no pages.
But the opposite is not working:
`/?s=term&post_type=page`
This is returning pages and posts.
How do I return only pages?
**Edit**
Forgot to mention, so I'm trying to allow the ability for the user to click two links at the top of the search results page.
<a href="/?s=term&post_type=post">Search Only Posts</a>
<a href="/?s=term&post_type=page">Search Only Pages</a>
So, I can't just globally set all search results to only be one or the other. | You can enforce a post type per callback on `pre_get_posts`:
is_admin() || add_action( 'pre_get_posts', function( \WP_Query $query ) {
$post_type = filter_input( INPUT_GET, 'post_type', FILTER_SANITIZE_STRING );
if ( $post_type && $query->is_main_query() && $query->is_search() )
$query->set( 'post_type', [ $post_type ] );
});
If that still includes other post types, you have a second callback registered on that hook. Try to find it; it might be a theme or plugin. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "search, post type"
} |
Ajax Comment: Page reloads whenever the comment submission form is reloaded
I noticed that when I'm trying to comment too fast in a page it's getting reloaded. I want to avoid reloading the whole page just because someone submits comments too quickly but I don't know where to start.
BTW, here's the ajax script I'm using. Since I'm really new on ajax and jQuery, I haven't been able to figure how to avoid the said issue, or if the said issue is in my ajax script. I'm also using underscores theme if that info would be relevant.
* * *
EDIT: I did some trial and error and noticed stuffs, changing the title for a more accurate description as well.
1. The reload problem don't happen when posting comments in rapid succession.
2. Submitting a comment for the first time reloads all contents under #comment element, and the reloading issue is starting when using the form inside the reloaded #comment element, e.g. when trying to comment on a second time. | I found out the issue. It was something like jQuery/AJAX code for it is not being able to hook itself when I reload the form with **.load()** , therefore the second time I submit a new comment, or when I clicked the reload button for the comment list/form (making the .load() run once), the new form would still submit the comment but since the jQuery/AJAX is not being run, the page reloads normally without AJAX.
I just changed the code from this:
$('#commentform').submit(function() {
.....
}
to this:
$(document).on('submit', '#commentform', function() {
.....
}
I'm glad that I've been able to pinpoit the issue, even if it took a long search and carefully selecting my search keywords on google. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "ajax, comments"
} |
Search content for shortcodes and get parameters
In content I can have multiple shortcodes like `[book id="1"] [book id="14" page="243"]`
Is there any help method with which I can search the content for that shortcode and get its parameters? I need to get IDs so I can call WP_Query and append the Custom Post Types titles at the end.
function filter_books( $content ) {
// get all shortcodes IDs and other parameters if they exists
...
return $content;
}
add_filter( 'the_content', 'filter_books', 15 );
I tried using following code but var_dump($matches) is empty and if it would work I am not sure how would I get parameters (<
$shortcode = 'book';
preg_match('/\['.$shortcode.'\]/s', $content, $matches); | This is working for me
$shortcode = 'book';
$pattern = get_shortcode_regex();
// if shortcode 'book' exists
if ( preg_match_all( '/'. $pattern .'/s', $post->post_content, $matches )
&& array_key_exists( 2, $matches )
&& in_array( $shortcode, $matches[2] ) ) {
$shortcode_atts = array_keys($matches[2], $shortcode);
// if shortcode has attributes
if (!empty($shortcode_atts)) {
foreach($shortcode_atts as $att) {
preg_match('/id="(\d+)"/', $matches[3][$att], $book_id);
// fill the id into main array
$book_ids[] = $book_id[1];
}
}
... | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "filters, shortcode, content"
} |
How to get file URL from media library
I am attempting to copy a file from an external URL and then reference the local copy of the image via a WordPress shortcode.
So far I have managed to copy the external image to the media library using `media_sideload_image()`, but am unable to find a solution to retrieve the newly uploaded file and use it within an tag.
Does WordPress offer any solution to find a file within an unknown subfolder in the media library? Or is there a method of copying an image with `media_sideload_image()` to a specific directory in the media library? | If you check the documentation for `media_sideload_image()` it _returns_ HTML `img` tag for the image right away. Alternately it can return just the URL.
Note that while this is suitable for _immediate_ use, it's generally challenging to go back from URL to attachment ID. IDs are much more friendly for many things, such as being stored, processed, used to access image sizes, and so on.
If there are intermediary steps in your process you might want to use deeper level `media_handle_sideload()`, which returns ID for the attachment rather than processed HTML. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "images, media, media library"
} |
Display div only on the HOMEPAGE
I would like to display a div, only on the _homepage_. Is this possible?
I have a banner in the _header.php_ file and only want to display this banner div on the homepage.
How could I achieve this?
Thanks in advance. | Depending on your setup you could use the conditional `is_home()` or `is_front_page()` like this:
<?PHP if( is_home() ) { ?>
<div> … </div>
<?PHP } ?>
See also the question "When to use is_home() vs is_front_page()?" for further details on the defferences between the two…
PS: you should consider using a child theme for this. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "theme development"
} |
Using wp_localize_script in template file - is it secure?
I have the following code inside one of my template files (NOT functions.php)
$datatoBePassed = array(
'pageTitle' => get_the_title()
);
wp_localize_script( 'main-js', 'php_vars', $datatoBePassed );
I am wondering if there are any inherent security issues when doing something like this outside of functions.php. My goal here is very simple- I'm just passing the page title into JavaScript so that way it can highlight matching text red within an existing list. I know there are probably better ways to accomplish this, but this is the best solution at the moment. If this is insecure, I can just echo it out into a `display:none` div, and read that instead. | Input/output related security issue can be roughly sorted into two buckets:
* someone manages to read information they are not supposed to;
* someone manages to write information they are not supposed to.
Localize is not capable of _writing_ anything into site, so you are safe on that front.
On the read side it's not much different from just echoing things into page source (which it's essentially doing). The only thing you need to be careful about is that data provided cannot be manipulated by user/input.
For example page title should be precisely for the page being processed and there should be no holes allowing it to return title for a _different_ page (which might be private and such). | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions, security, wp localize script"
} |
Is WordPress vulnerable to the httpoxy?
Is WordPress vulnerable to the httpoxy exploit? See < Thanks. | If I follow the description right the vulnerability refers to PHP applications which read, trust, and use `HTTP_PROXY` environment value (which might be compromised).
From quick search through WordPress core source code I found **no** instances of that value being accessed.
Since WP ships its own HTTP client implementation its also not affected by upstream library issues (such as Guzzle example). Though I think Requests library is being merged into core in near future, but it doesn't seem to be mentioned as vulnerable on that site.
So I would cautiously guess that WordPress _core_ is fine about it. Of course extension space is anything goes. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 6,
"tags": "security"
} |
Filter, or any way to dynamically change theme screenshot image?
I'm building a web application on top of WordPress. Part of this will be to automatically reconfigure theme assets based on the industry my user is aligned to. For example, the theme will auto-select from a library of stock background or slide-show images, based on the logged-in user's industry.
I'd like the user to also see theme snapshots that match their industry, so theme selection will look nicer.
Aside from creating a bunch of child themes, is there any way I can dynamically change the theme `screenshot.png`?
The only idea I've come up with so far is to directly manipulate the DOM with JQuery on the client side. I'd love a server-side solution, instead. | From quick look WP seems to process array of theme data in a way that is used for both PHP and JS sides.
Result passes through `wp_prepare_themes_for_js` filter, which seems like a suitable place to override screenshot URL as necessary.
This worked in my dev install:
add_filter( 'wp_prepare_themes_for_js', function ( $themes ) {
$themes['r-test']['screenshot'][0] = '
return $themes;
} );
Of course the nuance is that theme has to be _running_ for its code to execute. If you need to do this for inactive themes the code would have to be placed/running outside of them. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "plugin development, theme development"
} |
Change media item permalink
I have an image whose permalink is domain.com/books I would now like a page located at this permalink.
Is there a way to change the image's permalink?
Thanks | Yes!
1. Go to your Media Library
2. Find the Image
3. Click Edit
4. Locate the Permalink under the Title
5. Click Edit
6. Change the Permalink
7. Click Update!
## Edit
If for some reason you cannot Edit the Images' Permalink... you could:
1. Delete Image
2. Change your Pages' Permalink
3. Re-Upload Image | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 22,
"tags": "permalinks"
} |
How to ignore pagebreaks for RSS feed?
I use default page break tags in my posts and unfortunately RSS feeds do not show the full content without the page breaks. I am currently using WordPress 4.5.3.
I have "For each article in a feed, show" settings set to "Full text".
What can be the problem and if this is not a problem, what's the best way to fix this in my case? | If you mean how to ignore `<!--nextpage-->` in the feed content, then we can adjust this approach for feeds:
/**
* Disable content pagination for feeds
*/
add_filter( 'content_pagination', function( $pages )
{
if ( is_feed() )
$pages = [ join( '', (array) $pages ) ];
return $pages;
} );
where `$pages` is an array that contains the content parts. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "pagination, rss"
} |
Have Wordpress generate a JSON of the content
This particular project is huge, both in data and in user access (personaly I wouldn't use WP but the client wants to).
The problem is, I don't want the front-end to constantly access the database, so is there a way to make WordPress generate a JSON that I can use in the front-end?
I found one called WORDPRESS JSON API, but it doesn't seems to do this, it still access the DB on each request. | After pondering your question some I am guessing you mean to generate actual physical JSON file in filesystem to use as data source? That would certainly be unorthodox in WP development.
Typically in WP you try to minimize disk access, since it is more likely to be a bottleneck _in general_. Doing file writes is quite inconvenient in WP extension meant for public distribution, but in private of specific server you could generate and dump JSON into a file rather trivially.
For a more "WordPress way" of doing things you might want to look into persistent Object Cache. WP can be made to use persistent memory cache (such as APC, Memcache, Redis, etc), which both greatly increases its general performance and makes it possible to cache data there via WP APIs. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "json"
} |
Best way to move a site to a subfolder for testing purposes?
I have to make several changes to a website, and I'm willing to setup a copy of the current one on a subdirectory, on the same server.
I.E. if my site is `www.example.com`, what I'm trying to do is to fully copy it to `www.example.com/new/`, make all the necessary modifications, then, once it is done, copy it back to the main directory.
I know that it is not a simple matter of moving files, I guess that this is a complex matter involving different file paths and database entries. I'd like to know how can I safely do it and it the whole process has to be done manually or if there are some automatic tools (i.e. plugins) that can help me doing it without mistakes. | I have discovered that the easiest way to migrate a site is by using the Duplicator plugin; it manages both files and database. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "customization, backup, testing"
} |
Query posts only without featured image
want to query 100 posts, but only those which do not have a featured image attached. I am using meta_key method for this with WP_Query as such:
$args = array(
'post_type' => 'post',
'posts_per_page' => 100,
'meta_query' => array(
array(
'key' => '_thumbnail_id',
'compare' => 'NOT EXISTS'
),
)
);
But Not work with me
Any help ? | Try this code , its working for me
value=>'?'
because(value was required for `NOT EXISTS` comparisons to work correctly prior to 3.9. You had to supply some string for the value parameter. An empty string or `NULL` will NOT work. However, any other string will do the trick and will NOT show up in your SQL when using `NOT EXISTS`.)
For more information about `value=>?` please refer this link
$args = array(
'post_type' => 'post',
'posts_per_page' => 100,
'meta_query' => array(
array(
'key' => '_thumbnail_id',
'value' => '?',
'compare' => 'NOT EXISTS'
)
),
);
$new_query = new WP_Query( $args ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "wp query, post thumbnails"
} |
Should we use plugins that aren't available from the official WordPress site?
I'm not sure if my question is appropriate here, apologies in advance but I am confused and need some helpful thoughts!
We were using this plugin for our site , which has recently been removed from the WordPress site, and replaced with a suggested alternative. The alternative is very expensive and beyond our budget.
My site recently got hacked, and some spam links were included in some of the plugin files, including this one.
As the plugin is no longer supported, and hence there won't be any security updates, is this a source of vulnerability? | There is no definite answer as each plugin, whether available in a repo or not, should be handled on its own merit. Also, who says that that plugin caused your site to get hacked, it might have being a loophole in another plugin or even your theme.
Just in general, one should avoid using plugins and themes that are not actively being maintained as it does have an increased security vulnerability | stackexchange-wordpress | {
"answer_score": 14,
"question_score": 3,
"tags": "plugins, security"
} |
How to use force_feed with fetch_feed
I use the exact same code from Wordpress codex here : <
It works as intended with most external RSS i tried to use but for one of them i have the error
> A feed could not be found at _RSS-URL_. A feed with an invalid mime type may fall victim to this error, or SimplePie was unable to auto-discover it.. Use force_feed() if you are certain this URL is a real feed.
I can't find any information on how to use force_feed with the code `$rss = fetch_feed('RSS-URL');`, and i'm 100% sure the external rss code is valid. I think the problem from the RSS is the content type which is `xml` and not `rss+xml`.
Any help appreciated, thanks ! | If we peek into the `fetch_feed()` function we see the instantiation:
$feed = new SimplePie();
where the object is made accessible through the `wp_feed_options` hook via:
do_action_ref_array( 'wp_feed_options', array( &$feed, $url ) );
where `$feed` is passed by reference.
This means we can adjust that object instance through the hook, before the `$feed->init()` is called within `fetch_feed()`.
_I searched this site for examples for you and found only onehere by @Firsh._ that sets `$feed->force_feed(true)` through the `wp_feed_options` hook. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "rss"
} |
Is there a way to group specific CPTs under a single dashboard menu item?
My next project may involve dozens of CPTs (it's a ad board and each category would be a CPT, for example CARS and associated special attributes like mileage, gas/petrol and such as custom fields).
By default CPTs are accessed from a menu item in dashboard left sidebar. I don't want left sidebar to be 6 screens tall so is there a simple way to group specific CPTs into a sub-menu under one single sidebar menu item? | Use the `'show_in_menu'` argument of `register_post_type()` to specify the URL path of the parent menu item. For example, a value of `'edit.php'` will nest the CPT's management pages in the **Posts** menu item, `'edit.php?post_type=page'` will nest them in the **Pages** menu item, and a value of `'users.php'` will nest them in the **Users** menu item. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types"
} |
Render the metabox input values as HTML
I'm new to PHP and WordPress.
I've created a site on WordPress, where the user can add an HTML code snippet (the inputs are taken using a metabox and displayed). The problem is WordPress doesn't render the input's value, rather it converts it to ASCII and displays the HTML code snippet as raw HTML rather than rendering it.
Is there any solution for this? In certain parts of the template I would like to display the rendered HTML, and also the escaped (raw) HTML.
Please note that I am using a custom metabox in a custom post type. I generated the metabox using this generator. | When you want to output trusted html, use `html_entity_decode`.
$orig = "I'll \"walk\" the <b>dog</b> now";
$a = htmlentities($orig);
$b = html_entity_decode($a);
echo $a; // I'll "walk" the <b>dog</b> now
echo $b; // I'll "walk" the <b>dog</b> now
You can find more examples here. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, metabox, escaping"
} |
Remove "Comment" column in all post-types
I just want to remove **Comment's column** in **all post-types** and in a **single function**
 {
unset($columns['comments']);
return $columns;
}
add_filter('manage_edit-post_columns','remove_post_columns',10,1);
function remove_page_columns($columns) {
unset($columns['comments']);
return $columns;
}
add_filter('manage_edit-page_columns','remove_page_columns',10,1);
**Possible to do in a single function** and for future post-types ? | **I got an alternative :**
_This will not just hiding but disabling also_
function disable_comments() {
$post_types = get_post_types();
foreach ($post_types as $post_type) {
if(post_type_supports($post_type,'comments')) {
remove_post_type_support($post_type,'comments');
remove_post_type_support($post_type,'trackbacks');
}
}
}
add_action('admin_init','disable_comments'); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "comments, wp admin, columns, post type"
} |
Content only on last page, if the page has pagination
I want to show a donate button after the post and on the LAST page of paginated posts. While my code totally works, it is probably not the best way to do that. Has anybody a more elegant solution? Since the content (the donate button) is exactly the same, there is no need to call this HTML block twice. Thank you!
global $multipage, $numpages, $page;
if( $multipage && $page == $numpages ) { ?>
Content (on the last page of a paginated post)
<?php }
if ($multipage == 0) { ?>
Content
<?php } ?> | Instead of using the global variables directly, here's a way to use the `content_pagination` filter to add custom HTML to the last content page:
/**
* Append HTML to the last content page, if it's paginated
*/
add_filter( 'content_pagination', function( $pages )
{
if( count( $pages ) > 1 )
$pages[count($pages)-1] .= '<div>MY HTML HERE!</div>';
return $pages;
} );
This appends the custom HTML to all last content pages, where there is content pagination.
**Update:** To include posts without content pagination, we can e.g. replace `> 1` with `> 0`. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "pagination, content"
} |
Custom columns doesn't appear in custom post type
Hi i have a 'tour' custom post types and when i add a custom column at this post type there is not any custom column at tour post type my code is here
function tour_price_col( $column, $post_id){
switch ( $column ) {
case 'price':
echo get_post_meta( $post_id, 'tour-price', true );
break;
case 'test':
echo "salam";
break;
}
}
add_action('manage_tour_posts_custom_column', 'tour_price_col', 10 ,2); | First, you need to declare/register the new columns:
add_filter( 'manage_tour_posts_columns', 'cyb_add_new_columns' );
function cyb_add_new_columns() {
$columns['price'] = __('Price column title', 'cyb-textdomain' );
$columns['test'] = __('Test column title', 'cyb-textdomain' );
return $columns;
}
Then, you can print the content of the column for each post:
add_action('manage_tour_posts_custom_column', 'tour_price_col', 10 ,2);
function tour_price_col( $column, $post_id){
switch ( $column ) {
case 'price':
echo get_post_meta( $post_id, 'tour-price', true );
break;
case 'test':
echo "salam";
break;
}
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, columns"
} |
Font Awesome stopped showing icons, shows &# text instead
after migrating my WP site to a different domain and making adjustments, Font Awesome stopped showing icons and shows some weird text instead, for example & # 61505; (I can't copy it as a text, looks like an automatically generated graphics).
Please see attached image. . It will change all the old urls to the new ones.
This is what you're wanting, correct?
If there are any hardcoded paths in your template files (hopefully not!) you'll have to change those manually. Velvet Blues just addresses the database. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "paths"
} |
Autogenerate a Table of Contents
I am trying to generate a Table of Contents at the top of each of my posts and would like to minimize the requirements on the author. Ideally, the author would enter only various levels of the header tag along with an anchor link -- e.g. `<h1 id="introduction>Introduction</h1>` \-- and the WP function would scoop all the header tags' text content and links to generate the table.
While this would be relatively straightforward to do in the browser with JS, that feels hack-y to me and would hurt SEO. Is there a good way to do this server-side? | Sure. In your `single.php` or where you loop through the posts, start by getting the content:
$content = get_the_content();
Then use a regex where you target anything within `<h2>` tags:
$regex = '/<h2>(.*?)\<\/h2>/u';
And then use `preg_match_all()` to find all titles:
preg_match_all($regex, $content, $table_of_content);
This will create a multidimensional array, see:
print_r($table_of_content);
So you have the titles stored in `$table_of_content[0]`.
Using this array, and a variation of the regex to get the id **or** data-attribute which I would go with, you're set to go. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugin development, functions"
} |
WordPress, modular content, and syndication
I am trying to sketch out a possible Wordpress based solution by which content is authored in a modular way, with an arbitrary number of different modular blocks of content, (similar to Sir Trevor < that would also allow full content to be pushed (or pulled) to other separate WordPress installs. (The essential idea being that a set of editors have access to a set of simple modular blocks to build content which is likely to be duplicated across different separate sites and another set of editors have access to a more complicated set of blocks to build content that is not necessarily meant to be duplicated.)
It seems likely I could architect something with ACF, but I'm not sure that I could reliably duplicate that custom field based content between WordPress installs. Is there an obvious solution I'm overlooking or just ignorant of? | Currently there seems to be no option for building a WordPress-based system in this way, short of building something yourself. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, api"
} |
Batch process: remove first image from post content
I already added a featured post image to all my posts (>1000). Some posts (around 700) still have an image at the beginning of the post content.
Now I need to remove all images which are right at the beginning of the post content. I need to leave the images untouched which are not at the beginning.
Because of that I can't just remove "the first image tag occurrence in the post" because then I would remove images from the post content.
Maybe this plugin here Permanently remove first image from posts could be used as a base but what would be re regex or query to reflect this requirements? | Suppose you haven't modified anything to change the default content output, maybe this can help:
add_filter('the_content', function($content)
{
$content = preg_replace('~^<p><img([^>]+)></p>~i', '', $content, 1);
return $content;
}, PHP_INT_MAX); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "posts, images, content"
} |
Plugin translations problem
I developed a plugin for my client in english by default. I created estonian and russian translation files. But my client installed wordpress with estonian language by default and now, **when my plugin is activated it doesn't use estonian translation file, because I guess wordpress uses estonian language by default.** Russian language works well.
Client uses qtranslate-x plugin for translations. What should I do to solve this problem? | I am not confident without downloading Estonian copy of WP source, but from look at GlotPress it seems that locale code for it is simply `et`, not `et_EE`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, plugin development, translation, plugin qtranslate"
} |
Both the require and add_template_part function are not including the file
I'm trying to add a require function in my `functions.php`, to include a file that is in the `wp-content` folder. I first tried this with the function `content_url . 'filename.php'`So the line of code looked like this: `require(content_url . 'filename.php'`. However this made the site crash, because of a `die()` probably. After that I tried to just use the direct link, so `require(' but this also made the site to crash. Then I tried to use the `add_template_part` function, and for that I of course moved the `filename.php` file into the theme folder. Again this caused the site to crash. It looks like including is not allowed at all, since I can open the files in my browser. For testing purpose I changed the content of `filename.php` to `echo "Form here";`, and if I open this file in my browser directly, I indeed see Form here.
Could there possibly be anything I'm not seeing? Any suggestion is welcome! | Using an URL to include a php file will usually not work. You will need a filesystem path. Depending on where you .php file is located (in this case the template directory), you could use:
include( get_template_directory() . '/myfile.php' );
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, get template part"
} |
Rewrite rule : custom post type with 2 numeric variiables
I have a wordpress site using a custom post type "gallery" to show some photos. I can't find the right regex to match my url variables (i'm a novice with regex)
What i want to achieve is to get this form of url :
/custom_post_type_slug/custom_post_type_name/page_num/photo_id/
in my case it should give :
/gallery/name-of-gallery/1/15/
I've tried this regex :
add_rewrite_rule( 'gallery/(.+?)(?:/([0-9]+))?/([0-9]{1,2})/([0-9]{1,2})/?$', 'index.php?gallery=$matches[1]&page=$matches[2]&photo=$matches[3]','top' );
with no success.
When I test this rewrite rule with Query Monitor it tells that photo=$matches[3] and page is null.
If someone could give me an advise it will be very nice. | `add_rewrite_rule()` cannot automatically create that permalink structure for you. You should use wp_link_pages_link filter. E.g:
add_filter('wp_link_pages_link', function($link, $i)
{
global $post, $photo_id;
if ($photo_id && 'gallery' === $post->post_type)
$link = $link . '/' . intval($photo_id) . '/';
return $link;
}, PHP_INT_MAX, 2);
Then, you must use add_rewrite_tag() to make WordPress aware of `photo` query string:
add_action('init', function()
{
add_rewrite_tag('%photo%', '([0-9]+)');
add_rewrite_rule('^gallery/([^/]+)/([0-9]+)/([0-9]+)/?$', 'index.php?post_type=gallery&name=$matches[1]&page=$matches[2]&photo=$matches[3]', 'top');
}, 0, 0); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "rewrite rules"
} |
qtranslate-x problem with custom term description
I use qtranslate-x plugin for site translation. Works well, but on my custom term's page I see description in all languages.
; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom taxonomy, taxonomy, terms, plugin qtranslate"
} |
How to Create Custom HTML Tag on Editor in `Text(HTML)` mode
Can you please let me know how I can add a custom Tag button into WP Editor in `Text(HTML)` mode like
 but I only need products A, B and C to contain this HTML bit and the rest to stay with the default content. A, B and C are in the same product category. How would you narrow the products, via category or product by product, that will contain this HTML, please? | check the documentation to add something for a particular posts/pages/category < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "customization, woocommerce offtopic, html"
} |
How to filter url on post submission?
I would like to swap out image URLs upon post submission on both `content editor` field and a custom field `cover_image` of a custom post type `article`.
For example, the original content may contain image url such as:
<img src="
I would like to swap it to:
<img src="
And have it stored permanently to the database.
How to edit the regular expression is not my concern, but where to make the edit to insert the regular expression is what would like to know.
Is there some kind of filter that I can use on post submission? | `save_post` didn't work for me.
What works in my situation is using content_save_pre filter or the content processing before save.
Since I'm using `Advanced Custom Field` plugin for my `cover_image` field, and I ended up using `acf/save_post` filter to process the field. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, posts, filters, regex, post content"
} |
Div Missing In Custom Loop Query
I'm using a customized php code for my wordpress loop. The code is designed the break the post up to be styled differently via html & css. The code is also designed so that I can add div blocks in between the post.
See the photo below for an example of the code's use.
Here is the code below that I am using.
<
My Problem is that the DIV that's suppose to come before the last 10 post is not showing up. I don't believe that it's an issue with my css file, but if you need those files too here they are.
Full Index.php file with HTML/PHP
<
Full CSS File
<
Here is a photo of what I am trying to accomplish.
 :
if ($count === 10) echo 'DIV/CONTENT BEFORE THE NEXT 10 POST GOES HERE';
The first conditional fails when `10 === $count` and so the second conditional can never succeed.
As your while loop executes (in a structure that WordPress calls The Loop, calling function `the_post()` to advance through the list of posts you are processing to generate this web page) `$count` is incremented as a way of keeping track of which post the code is working on.
When Bernie Sanders is being processed `$count === 1`, when we get to Drake's Album `$count === 4` and so on until every post on the page has been rendered. The code doesn't have sections of posts with their own counts, there's just a count from the top, so your Jeep ad needs to be inserted when `$count === 15` according to your picture. I'm not completely sure, as you have a block of 6 posts labelled as "next 9." | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, loop, query posts"
} |
undefined function apache_request_headers()
I'm trying to run the following command locally:
/usr/local/bin/wp plugin deactivate "EG Fulltext Search" --allow-root
And I get the error `undefined function apache_request_headers()`
Here is the wp info:
PHP binary: /usr/bin/php
PHP version: 5.5.37
php.ini used: /etc/php.ini
WP-CLI root dir: phar://wp-cli.phar
WP-CLI packages dir:
WP-CLI global config:
WP-CLI project config:
WP-CLI version: 0.24.0-alpha-95a84de
This is running apache on Centos 7. Php is running as Apache 2.0 Handler.
I used the nightly version but I also get this error the latest stable release.
I'm really stuck on this at the moment and can't use the wp commands so any help would be really appreciated. | From quick search I cannot find calls of this function in neither WP core or WP CLI.
From quick check of documentation for it it seems that support for it in CLI context is (relatively) recent — starting with PHP 5.5.7.
You might want to check if your PHP up to date. Note that CLI might be running different/older PHP version from web server. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp cli"
} |
Acf Pro repeater field returns null when call inside foreach
I have a problem with the repeater field in Acf Pro. I want to retrieve fields inside the foreach but it gives me "null" value.
Can someone help me?
My code:
function label_text( $post_id = '' ) {
while( have_rows('description', $post_id) ): the_row();
$description .= get_sub_field('label') . get_sub_field('text');
endwhile;
return $description;
}
foreach ( $query->posts as $id ) {
$label_text = label_text( $id );
$logo = get_field('logo', $id);
$results[ get_the_title( $id ) ] = array(
'id' => $id,
'description' => $label_text,
'logo' => $logo['url'],
'type' => get_post_type($id),
);
} | I found a Notice error in your code. You have used $description in your code. Initially you have not defined it and directly using concatenation to it.
function label_text( $post_id = '' ) {
$description = '';
while( have_rows('description', $post_id) ): the_row();
$description .= get_sub_field('label') . get_sub_field('text');
endwhile;
return $description;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "advanced custom fields"
} |
Wordpress, how to figure out how to edit front page
I am currently using the Onepress theme and want to edit the header section, the part that prints the site title. However, I cannot for the love of life figure out which part actually controls the header. Header.php does not show anything and neither does the frontpage template. | In WP, you first need to understand the template hierarchy <
So as per hierarchy,
\-- front-page.php
\-- home.php / custom page template.
If you have front-page.php , then please check which header file it is enqueuing.
If there is no front-page.php then check home.php exist in your theme file. If yes check which header file it is enqueuing .
If it doesn't have both file, goto Appearance >> Customise >> Static Front Page.
, then it will use header.php from your active theme.
If it has get_header( 'home' ); then it will use header-home.php
So from there you can go customise your header.
Also if you are using child theme , then please make check if it has header related file in your child theme or not.
Thanks | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "frontpage"
} |
execute custom function on database connection error
is it possible to execute a function on wordpress db connection error? I mean is there any hook or something in the (error stablishing database connection) thing...? I want to do something when I get to that error. | We you want to customise your Error Establishing Database Connection to something else then you need to create a file.
Here is the documentation for that
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "database, actions, wp config"
} |
How do I disply an array inside a custom post type?
I tried to create a table output with the content of a custom post.
I can echo my city properly:
<span style="font-weight: bold;">city: </span>
<?php echo get_post_meta($post->ID, 'ptn_plaats', true);?>
But with this next line I get echo me ARRAY instead one of the options !!
<span style="font-weight: bold;">Systeem :</span>
<?php echo get_post_meta($post->ID, 'ptn_systeem', true);;?>
How can I echo the contents of my custom post type? | You got ARRAY echos because you saved array on post meta,
Just check array values of meta data like:
print_r( get_post_meta($post->ID, 'ptn_systeem', true) );
and echo it like:
foreach( (array) get_post_meta($post->ID, 'ptn_systeem', true) as $option):
echo $option . "<br>";
endforeach; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, array"
} |
How to add nofollow site-wide
I'd like to change the meta robot tag on my site to be `noindex` and `nofollow`. When I set the WP settings in "Search Engine Visibility" to "Discourage...", it only generates:
<meta name='robots' content='noindex,follow' />
How can I change it to `noindex` and `nofollow`? | One part of removing your site from Google is to add `<meta name='robots' content='noindex,follow' />` to every page. If you can edit the theme code then you could just add this to `header.php` (and any variants).
You could also use a plugin. I've not tested any, but < claims to do the job simply. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "nofollow"
} |
Performance when getting post meta for post retrieved by meta value
I have a meta key which I would like to use to get all post meta data for a post where that one meta key matches a specific value, in one go.
Example: `Post 1` has a `meta_key` called `unique_number`. I want to query for all the occurences where `unique_number` is a specific value, and then get all the meta data for the posts where `unique numner` is that value.
The way I found to do it now, is this way:
$args = array(
'meta_key' => 'unique_number',
'meta_value' => '12345'
);
$posts = get_posts( $args );
...then I have to loop through the result and use get_post_meta to fetch the meta data.
Is it possible to do this in one query, except many, with built in Wordpress functions, or do I have to write my own custom mysql query? | When you call get_posts WP will also retrieve and cache all the post meta, so your later calls to get the meta data shouldn't cause any more database queries. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "wp query, post meta, mysql, meta query"
} |
How to delete categories in WordPress
I'm trying to delete a category in WordPress but i can't find out how. Thank you! | To delete a category from WP , first you need to open the category listing. It will come when you will mouse over the Posts.

How do I create a custom meta box for posts which have a boolean data type and can be true only for one post. I want it to be falsified for all other posts when it's set on one post.
1. Is there a hook that runs right after a custom field is saved in the create post screen?
2. Is there a way to do this with the metabox plugin?
3. For example if you want to create a featured post feature, only one post can be a featured post. Is there a way to create a single featured post without using custom meta boxes? | Storing of your own meta fields is typically a custom process, more so if you are using a third party framework.
Technically it's possible, but clunky:
1. Hooking into `save_post` would allow you to check if meta is added to it
2. If so you can immediately query for _previous_ (if any) post that had it and unset the meta for it
However I concur with the comment you got that this does not essentially seem to fit a purpose of post meta well. There are precedents in core itself (for example front/posts page handling) to store such things as post's ID in an option. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom field, metabox, featured post"
} |
export and import taxonomy terms from one taxonomy to another
* I have a custom taxonomy named _"places"_ and another taxonomy named _"featured places"_.
* On the _"places" taxonomy_ i have 150 terms (names of places) and i want those same 150 names (terms) on the _"featured places" taxonomy_.
**Is there a way to just export the terms from the _"places" taxonomy_ and export it into the _"featured places" taxonomy?_**
Thanks! | Why not just change the label for the taxonomy "places" to "featured places" without changing the ID it is registered with and you'll achieve the desired effect without moving any data around! And then ditch the new but empty "featured places" taxonomy. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom taxonomy, terms"
} |
How to make Meta Query case sensitive?
I have a meta query similar to:
$posts = new WP_Query( 'post_type=article&meta_key=kln_aid&meta_value=' . $aid );
where I need `aid` to be case-sensitive. Is that possible via Meta Query? | This is how meta_key/_values work. How you store your values is case sensitive.
Example `meta_key = 'foo'` and `meta_value = 'Bar'`
Would return the result you are looking for:
$posts = new WP_Query( 'post_type=post&meta_key=foo&meta_value=Bar' );
Would not return the result you are looking for:
$posts = new WP_Query( 'post_type=post&meta_key=foo&meta_value=bar' );
However it does appear that your database can be setup as case insinsitive and cause some issues.
> Please note that if your database collation is case insensitive (has with suffix _ci) then update_post_meta and delete_post_meta and get_posts will update/delete/query the meta records with keys that are upper or lower case. However get_post_meta will apparently be case sensitive due to WordPress caching. See < for more info.
Reference: update_post_meta for more info | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "wp query, custom field, post meta, meta query"
} |
Create single.php for specific tag by tag id or name
i have multiple tags and want to create multiple single.php for everyone tag.
**How create single.php for tags??**
> This code working well for category, how to edit it for tags??
function my_category_templates($single_template) {
global $post;
if ( in_category( 'raspee' )) {
$single_template = dirname( __FILE__ ) . '/single-raspee.php';
}
return $single_template;
}
add_filter( "single_template", "my_category_templates" ); | `has_tag()` is a function that will check if a `post` has a certain tag
You could integrate it into your code like so:
function my_category_templates($single_template) {
global $post;
if ( in_category( 'raspee' )) {
$single_template = dirname( __FILE__ ) . '/single-raspee.php';
}
if ( has_tag( 'everyone' )) {
$single_template = dirname( __FILE__ ) . '/single-everyone.php';
}
return $single_template;
}
add_filter( "single_template", "my_category_templates" );
you can check out this function here: < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "functions, tags"
} |
Search: display all found matches inside post
I'm working on a custom search where I'm filtering results using custom taxonomies and categories.
The search works but on the results I want to display every match inside the post, for example if I search for 'juice' I want to display many excerpts of the post where the word 'juice' was found.
I don't want to display the entire post because these are very long posts, I just need the phrases where the word was found.
Can that be done using the WordPress search? | I found the following plugin that shows the results on many phrases of the same post:
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "search, query posts, excerpt"
} |
Adding pagination on template page wordpress
in the template page loop get posts from tag which name is raspee, post per page are 5. pagination show in the page but not working..
**What is problem in my code??**
> Template-page
<?php /* Template Name: Raspee */ ?>
<?php get_header(); ?>
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$original_query = $wp_query;
$wp_query = null;
$args=array('posts_per_page'=>5 , 'tag' => raspee );
$wp_query = new WP_Query( $args );
if ( have_posts() ) :
while (have_posts()) : the_post();
get_template_part('content');
endwhile;
next_posts_link();
previous_posts_link();
endif;
$wp_query = null;
$wp_query = $original_query;
wp_reset_postdata();
?>
<?php get_footer(); ?> | You have not add "paged" in WP_Query args array ,that's why your pagination not working. try this code , it will work definitely
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$original_query = $wp_query;
$wp_query = null;
$args=array('posts_per_page'=>5, 'tag' => 'raspee', 'paged'=>$paged);
$wp_query = new WP_Query( $args ); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 0,
"tags": "pagination, page template"
} |
store posts_id of category into a varable?
I have ten posts in my query that belong in three categories: cat-a,cat-b,cat-c.
I'm looking for a way to store $posts_ids from each category into a variable.
Say for example, if three posts are in "category-a" then store those posts_ids in a variable.
Cat-a
Post 1 ID->435
Post 2 ID->477
Post 3 ID->488
$idcata = 435,477,488
Cat-b
Post 1 ID->87
Post 2 ID->32
$idcatb = 87,32
Cat-c
Post 1 ID->876
$idcatc = 876
Thanks | For getting the posts related to each category you need to use `get_posts( $args )` function and in `$args` you can add your category_id
$args = array (
'post_type' => 'post',
'category' => $cat_ID,
'post_status' => 'publish',
);
$my_posts = get_posts( $args ); // return array of posts
// storing all post ID in an array
foreach( $my_posts as $my_post ) {
$post_cat_name[] = $my_post['ID'];
}
So in `$post_cat_name` it will store all the post id related to your `$cat_ID`
If you want these to be done for 3 `$cat_id`, then you can loop the above code for 3 `$cat_id` and you can use `$post_cat_name` array as `2D array`. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "posts, categories"
} |
How can I make a development copy of my site in a subdirectory to test out a theme?
I have purchased a WordPress theme and I want to test the theme on the same domain without removing the current theme.
For example:
* I have a WordPress website www.example.com (running with one theme)
* I want to install a new theme to www.example.com/new (with the new theme)
How can I do this? | You can create a development copy of the existing site by:
1. Copying all the existing files to the subdirectory.
2. Making a copy of the database and pointing to the database copy in the `/new/wp-config.php` file. You will need to change the options `homeurl` and `siteurl` in new database's `wp_options` table to add `/new/` to the end of it.
3. Login to the test site and install the theme and activate the theme to test it.
Alternatively there are staging plugins available that can do most or all of this process for you such as Duplicator and Sandbox.
Another possibility is to install the new theme on the existing site and test it with a tool such as Theme Test Drive plugin or Toolbar Theme Switcher. Usually you can configure the theme while testing it this way, but not always - it depends on how the theme saves it's settings. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "clone site"
} |
Authoritative answer on which boots first - Plugins or Themes?
I can't seem to find anywhere in the WordPress documentation an authoritative answer on the question on whether a WordPress plugin boots first or whether a WordPress theme boots first.
I need to know the answer because an important development decision I am working on depends on it - as it is related to themes that depend on the presence of certain plug-ins.
And by "authoritative answer", I mean -- is the answer as-it-is just an accident of how WordPress is presently designed - subject to being all up-in-the-wind next version of WordPress --- or is it a standard aspect of how WordPress is supposed to work? | See this famous answer by the equally famous Rarst. Here he charts out the load process of WordPress which hasn't and isn't expected to change any time soon. The process pretty much goes:
1. WordPress Core
2. Must-Use Plugins ( mu-plugins directory )
3. Plugins
4. Themes ( Child before Parent ) | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 3,
"tags": "plugin development, theme development, codex"
} |
How can I create a list of page titles from custom meta values?
I want to associate pages with other pages by using custom meta values.
For one page, I want to associate two other pages, so I create a custom meta value with the key `Procedure` and the value of the other page ID, one for each page.
Then I want to display these associated pages, as their page titles, but in a comma separated list:
<?php echo implode(', ',get_post_meta($patient_story->ID, 'Procedure', false)); ?>
This is nearly there, but it only displays the page IDs (as it's giving the direct values in from the custom meta entries). I can't seem to integrate `get_the_title()` without breaking the code.
What's the best way I can have it so that it will convert:
Meta Key Meta Value
Procedure => 238
Procedure => 240
into 'Page title 1, Page title 2' | You need to get the title for each post ID in your array. The straightforward way is this:
$procedure_title_list = array();
$procedure_list = get_post_meta($patient_story->ID, 'Procedure', false);
foreach ( $procedure_list as $procedure ) {
$procedure_title_list[] = get_the_title( $procedure );
}
echo implode( ', ', $procedure_title_list ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php, theme development, custom field, post meta"
} |
How to add custom variable in url without redirect?
I'm trying to add a local variable to my URL.
As an example I have this URL:
mysite.com/my-page-name/
And I want to add 'en' variable into it and leave the page working properly:
mysite.com/en/my-page-name/
I tried to deal with it using `add_rewrite_tag()` and `add_rewrite_rule()` but it isn't working so what am I doing wrong?
add_rewrite_tag('%locale%', '^([a-z]{2})');
add_rewrite_rule('^([a-z]{2})/(.+)[/$]', 'index.php?pagename=$matches[2]', 'top'); | It was just a mistake in regexp in rewrite rule. This one works perfectly!
add_rewrite_rule('^([a-z]{2})\/(.+)(\/)?$', 'index.php?page=&pagename=$matches[2]&locale=$matches[1]', 'top'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "url rewriting, urls, rewrite rules, rewrite tag"
} |
How are readers authenticated for leaving comments?
I'm thinking of creating a WordPress blog, not on WordPress.com but just using WordPress on a hosted website. I would like to allow comments on the blog, but was wondering in what way are commentators authenticated. (I don't have experience with WordPress.) Are passwords stored in plaintext? Are their hashes stored? Is bcrypt used? Are their credentials stored in the site's database or are they offloaded to WordPress.com? The point is - I don't want to create a security issue for users. | By default passwords are encrypted using 8 passes of MD5. There are other ways to configure the password encryption. (<
The hashes are based on custom keys setup in the wp-config file when creating the site.
They are stored locally and not on Wordpress.com
You can make users register to leave comments or you can open them up to the public. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "comments, security, authentication"
} |
how to add custom wp_nav_menu class css selector to ul and a tags?
crafting a theme from finished html/css markup and wonder how to wrap `a` tags in my custom class? With `ul` wrapper this is works:
wp_nav_menu(
array('menu' => 'menu-header',
'menu_class' => 'list',)
);
but how to deal with menu items, and with currently selected menu item? I need `ul` to be with `.class` selector and `li` with `.item` selector as well | The following example adds a unique CSS class to a single, specific nav menu item.
function my_special_nav_class( $classes, $item ) {
if ( is_single() && $item->title == 'Blog' ) {
$classes[] = 'special-class';
}
return $classes;
}
add_filter( 'nav_menu_css_class', 'my_special_nav_class', 10, 2 ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "menus"
} |
How can you alter the name of attributes in a shortcode?
I'm trying to write a shortcode for a button, here's how it looks
/**
* Button Shortcodes
*/
function btn_shortcode( $atts, $content = null ) {
$a = shortcode_atts( array(
'class' => 'btn',
'href' => '#',
), $atts );
return '<a class="' . esc_attr($a['class']) . '"' . ' ' . 'href="' . esc_attr($a['href']) . '">' . $content . '</a>';
}
add_shortcode( 'button', 'btn_shortcode' );
It works like this `[button class="btn btn-primary" href="domain.com"]Learn More[/button]` but I'd like to change it to make it a bit easier for someone to come in and modify these things, I'd like the shortcode to look like this `[button class="btn btn-primary" link="domain.com"]Learn More[/button]`, so I changed `href` to `link`. | function jk_WPSCEX_add_message( $atts )
{
$output = '<a href="' . $atts['link'] . '">' . $atts['text'] . '</a>';
return $output;
}
using the above function shortcode is generated in the form of `[jk link=" text="Like me on Facebook"]`
OR For Enclosed type of shortcode:
function jk_WPSCEX_add_message( $atts, $content = null )
{
$output = '<a href="' . $atts['link'] . '">' . $content . '</a>';
return $output;
}
shortcode to be used is `[jk link=" us on Facebook[/jk]` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "shortcode"
} |
How to set page title tag in custom template for non-Custom Post Type?
I have this code in my custom template file:
<?php
/*
Template Name: custom-template-view
*/
ob_start();
get_header();
function assignPageTitle(){
return "my page title";
}
add_filter('wp_title', 'assignPageTitle');// not working
add_filter('the_title', 'assignPageTitle'); // not working
?>
<div>MY CONTENT</div>
<?php get_footer(); ?>
I want to set custom title tag but it is not working. In this template I am showing records from custom table. | Template files are not the right place to add in functions like that. The template file isnt loaded until late in the hook/filter process. Your function should be in functions.php. This way it can be added in before your tempalte files load, and functions that are in use in them can be altered.
Often times `wp_title()` is used in the header.php so it possible you are using that, but form the code you show you are filtering functions you are not using. Except maybe in header.php, but its loaded and executed before this custom template file. You also do not show the use of `the_title()` so I can not tell how/when/where this would actually filter anything if the function was placed in the right location. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "templates, metabox, wp title"
} |
Does get_template_part pull data once in a loop?
When i use the **"get_template_part();" inside a loop** , does it search for that template file **every cycle** of the loop (each post) **or** does it search for the file **once** and then reuse it every cycle of the loop? | `get_template_part()` calls `locate_template()`, and both functions are running `file_exists()` checks for the same file over and over. There is no caching. Meh.
But … PHP has an internal cache for file look-ups, so a direct file access will not happen on every call.
There is an edge case, most developers aren't aware of: A file can be deleted after the first access, and `file_exists()` will still return `true` if PHP's cache hasn't updated. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "loop, get template part"
} |
Can some vulnerabilities in plugins be exploited even when the plugin is inactive?
I just received a notification from the developers of the Wordfence security plugin of several vulnerabilities that exist in other popular Wordpress plugins. One example in this case is a mailchimp form plugin which is likely to be quite widely used.
I'm interested to know whether some plugin vulnerabilities can be exploited even if the plugin is inactive? (ie the plugin is present on a site, but currently not activated) | Yes, of course. If the PHP code in a file works when that file called separately, and if there is a vulnerability, it can be exploited.
There are two basic rules. They apply not only to WordPress, but to every web site:
1. Use only code that you understand completely.
2. Do not put unused code onto your server. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "plugins, security"
} |
Remove H1 / title / Underscore - without CSS
I have tried searching, and tried a few options, but I'm not able to remove the H1 / title / Underscore for specific pages.
I don't want use CSS. I would like to remove it via `functions.php` or in `content.php`.
I'm not good in PHP, so the Codex didn't help me too much.
I need something like this:
if > page slugs / IDs > do not display H1/ title
Can anybody help? Thanks. | The way I would do this is to create a separate page template that lacks the H1 code, and then manually select that template (in the Page Attributes box on the page editor screen) for each desired page. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "functions, title, underscore"
} |
How to remove the WordPress version from some .css/.js files
I know that I can use the following function to remove the version from all `.css` and `.js` files:
add_filter( 'style_loader_src', 'sdt_remove_ver_css_js', 9999 );
add_filter( 'script_loader_src', 'sdt_remove_ver_css_js', 9999 );
function sdt_remove_ver_css_js( $src ) {
if ( strpos( $src, 'ver=' ) )
$src = remove_query_arg( 'ver', $src );
return $src;
}
But I have some files, for instance `style.css`, in the case of which I want to add a version in the following way:
function css_versioning() {
wp_enqueue_style( 'style',
get_stylesheet_directory_uri() . '/style.css' ,
false,
filemtime( get_stylesheet_directory() . '/style.css' ),
'all' );
}
But the previous function removes also this version. So the question is how to make the two work together? | You can check for the current _handle_ before removing the version.
Here's an example (untested):
add_filter( 'style_loader_src', 'sdt_remove_ver_css_js', 9999, 2 );
add_filter( 'script_loader_src', 'sdt_remove_ver_css_js', 9999, 2 );
function sdt_remove_ver_css_js( $src, $handle )
{
$handles_with_version = [ 'style' ]; // <-- Adjust to your needs!
if ( strpos( $src, 'ver=' ) && ! in_array( $handle, $handles_with_version, true ) )
$src = remove_query_arg( 'ver', $src );
return $src;
} | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 7,
"tags": "wordpress version"
} |
Set up PHPUnit with WordPress: The WordPress tests are 3 - 4 years old; does it matter?
I'm trying to set up PHPUnit with WordPress, and the tutorial I found tells me to download this repository so that I can bootstrap the WordPress environment to run my tests. The only issue I have is that the repo was last changed 3 - 4 years ago, which is a long time.
I have also googled a little but, and found a guide for how to set up tests with PHPUnit in WebStorm, but that site were also linking to the same repo.
Does anyone have any experience using this, or using PHPUnit with WordPress? | That seems to be an old repo, you should use < Obviously trunk should be used if you want to use the tests with 4.6. Not sure how much difference there is in the infrastructure between the version (in other words, it is unlikely that you care how core does a specific test, therefor the staleness of the core tests might not be an issue at all) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "testing, unit tests"
} |
How to split long posts in multiple pages in twentysixteen
I am using twentysixteen WordPress theme, Whenever i tried to split long post in multiple page by tag nothing happened. Kindly help me. | You have to add **<!--nextpage-->** in Text mode of editor. If you add it through Visual editor - WP will escape it to HTML:
<!--nextpage-->
and display it literally (instead of pagination):
> <!--nextpage-->
So, check your post by switching to Text editor. If nothing isn't displayed at all when you view the post, this may be a plugin issue. Update your theme to the latest version and disable all plugins temporarily. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -2,
"tags": "pagination"
} |
Multiple installation in a single database
I would like to ask, can I install multiple wordpress in one single database? Will the new installation automatically get new table names that differentiate it with the existing ones? Or will it overwrite the existing one? | Yes, multiple installations can share a single database.
When you edit the `wp-config.php` file for each installation, you must give each install a unique table prefix.
The process is also explained in Installing Multiple Blogs: Single Database in Codex. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "database"
} |
How to add tags in Submenu page or Menu page
Is it possible to add tags(Like every post) in Submenu page or Menu page? Without creating custom post type.
I have Menu page and a form in it and I want to add tags in menu page. | It is possible. By default when you click on a tag link you visit that tags archive page. Just use that page. The following will show you how to add that link to the menu. If you need something more custom you will need some custom code, but the below will give you what you have asked for.
1. Visit any tag page you would like the link to go to and copy the URL.
2. Then visit the Admin Dashboard under Appearance you will see Menu.
3. Create a Custom Link
4. Paste in the URL you want give it a Title
5. Then Click Add to Menu Once the Menu Item is added
6. Move it to the desired location and Save | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugins, tags, add menu page"
} |
get url page template
I have created a page template where I need current page URL
I have tried
get_site_url();
and
get_permalink();
but it shows nothing.
Let me know is anything missing in code. | if you're using a page template, then if you want to get the current page URL you could try to use this function:
get_permalink();
or
echo get_permalink();
if you want to print the result | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "page template, site url"
} |
Allow only Admin role to access plugin settings/options page
I have created a plugin, but it seems that all roles (Contributor, Author, Editor, Admin) except Subscriber have access to the settings/options page for my plugin.
How do I set permissions for only Admin to be able to access my plugin options/settings page?
EDIT: Here is how I create the options page:
function myplugin_add_admin_settings_menu() {
add_options_page( 'MyPlugin Options', 'MyPlugin Options', 'read', 'myplugin-options', 'myplugin_options' );
}
add_action( 'admin_menu', 'myplugin_add_admin_settings_menu' );
function myplugin_options() {
//Display options/settings page here
} | The 3rd argument of `add_options_page` is the capability required for this page to be displayed to the user.
Then to allow only admin to use this page, you have to set a capability which is only owned by admin, like `activate_plugins`.
So change `read` to `activate_plugins` like this:
add_options_page( 'MyPlugin Options', 'MyPlugin Options', 'activate_plugins', 'myplugin-options', 'myplugin_options' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, user roles"
} |
How to hide an item from a menu to logged out users (without a plugin)
I want to hide an item from a menu if a user is logged out.
I am currently using the below code that achieves this using two separate menus, but to save duplication, I would like to only have to manage one nav menu.
function my_wp_nav_menu_args( $args = '' ) {
if ( is_user_logged_in() ) {
$args['menu'] = 'logged-in';
} else {
$args['menu'] = 'logged-out';
}
return $args;
}
add_filter( 'wp_nav_menu_args', 'my_wp_nav_menu_args' );
Is it possible to hide just one item for a logged out user, rather than doing it the way I currently am? | Find the class or id of the menu item that you want to hide. suppose the class of that menu is `logged-in-menu`
Then in header.php file of your theme before closing head tag use the below code
<style>
<?php if(! is_user_logged_in() ) : ?>
.logged-in-menu{
display: none;
}
<?php endif; ?>
</style> | stackexchange-wordpress | {
"answer_score": -3,
"question_score": 4,
"tags": "menus"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.