INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
CMB2 - array_search or in_array from repeat_group and comma separated values
I have this data coming from `$myoptions = my_get_option('my_repeat_group');`
`$p = 'T1X 0L6'; // find me`
`print_r($myoptions) =`
Array ( [0] => Array (
[region_name] => Alberta
[postal_codes] => T1X 0L3,T1X 0L4,T1X 0L5,T1X 0L6,T1X 0L7
[region_discount] => .5 )
[1] => Array (
[region_name] => Ontario
[postal_codes] => T1M 0W3,T1M 0W4,T1M 0W5,T1M 0W6,T1M 0W7
[region_discount] => .25 ) )
****
foreach ( $myoptions as $key => $value ) {
if ( in_array($p, $value['postal_codes'] ) {
// need to know $key of which array the $p was found,
// in this case, I would like to find [0]
}
}
I would like to find `$p` within `$value['postal_codes']`, and when I do find it, return the key in which it came from. | `$value['postal_codes']` is not an `array` it is a `string`, you either need to explode it like:
foreach ( $myoptions as $key => $value ) {
if (in_array($p,explode(","$value['postal_codes']){
// need to know $key of which array the $p was found, in this case I would like to find [0]
}
}
Or search on the string
foreach ( $myoptions as $key => $value ) {
if (strstr($value['postal_codes'],$p){
}
}
Or the most efficient way would be use array_search on the exploded like so:
foreach($myoptions as $key => $options) {
$keys_containing_p[$key] = array_search($p,explode(",",$options['postal_codes']));
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, plugin options"
} |
Redirect www.mainsite.com/subsite/wp-login to www.mainsite.com/wp-login
I'm using groupblog feature and hence multisite is required with it .
If a new user(not logged in) reaches any of the groupblog directly viz. a subsite and clicks the login button he's redirected to www.mainsite.com/subsite/wp-login.php whereas i want him to reach at www.mainsite.com/wp-login.php . How can i do this ? | I suppose `www.mainsite.com` is the main blog and `www.mainsite.com/subtitle` is a dynamic child blog. You can use MU api for this:
add_action("init", function(){
global $pagenow;
if ( 'wp-login.php' !== $pagenow ) return;
global $blog_id;
$main_blog_ID = 1; // main site ID (use get_current_blog_id() to get ID)
if ( (int) $blog_id !== (int) $main_blog_ID ) {
switch_to_blog( $main_blog_ID );
wp_redirect( wp_login_url() );
exit;
}
});
Hope that helps. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "multisite"
} |
If I define a variable in header.php, how do I make it available to templates?
I've defined a variable in my child theme header.php.
I'd like to get the value of this variable from one of the templates that is rendered after the request in which the header.php is called.
So, in header I've got this:
$foo = "bar"
If I test for this value with header.php, it returns "bar". But if I test for the value from a template called after the header gets called, I get 'null'.
The first thing I tried was putting 'global $foo' before the definition of $foo. But this didn't change my result. | It the template is called via `get_template_part()`, then it is in a new variable scope. to access it, you have to use the `global` keyword in you template file:
global $foo;
echo $foo;
As `header.php` probalbly is also called in a function scope, you have to make sure there the variable is used in global scope when definig it:
global $foo;
$foo = 'bar'; | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 1,
"tags": "php, templates, child theme, variables, get template part"
} |
Trying to remove white space between nav bar and content?
If you go to my site - www.sorensenes.com - there is at least an inch of white space between nav bar and the main picture on the page. How can I get rid of that white space and move the picture up closer to the nav bar? I have been searching online for most of the afternoon trying different suggestions but nothing is working...help!?!! | This is a CSS issue. Adding this to the bottom of your page will help.
<style>
body main#primary {
background: #fff;
padding-top: 10px;
}
main#primary .wrapper {
padding: 0px;
box-sizing: border-box;
}
</style> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "css"
} |
How to set value in Query Loop?
I have a Query:
<?php
$feature_big = array(
'posts_per_page' => '1',
'meta_key' => $count_today,
'orderby' => 'meta_value_num'
);
$wp_feature_big = new WP_Query( $feature_big );
?>
<?php if( $wp_feature_big->have_posts() ) : while( $wp_feature_big->have_posts() ) : $wp_feature_big->the_post(); ?>
/----------------------------here------------------/
<?php endwhile; endif?>
Now, i want change value (posts_per_page, meta_key,...) in 'here'. Is it possible? And How? Thank you! Sorry my English :) | You can run multiple nested WP_Queries as long as you `reset_postdata()` to get the outer loop back on track.
$query_args = array (
'posts_per_page' => '1',
'meta_key' => $count_today,
'orderby' => 'meta_value_num',
);
$outer_query = new WP_Query( $query_args );
while( $outer_query->have_posts() ) :
// conditional if
if( true ) {
// change the query arg in the inner loop
$query_args[ 'meta_key' ] = 'something_else';
}
// start an inner query with adjusted params
$inner_query = new WP_Query( $query_args );
// nested loop
while( $inner_query->have_posts() ) :
// ...
endwhile;
// After looping through a nested query, this function restores the $post global to the current post in this query.
$outer_query->reset_postdata();
endwhile; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "posts, query"
} |
How to populate data from JSON using AJAX in TypeScript?
I have data attribute in my HTML page. I have a JSON file "rss.json". I am not getting the typescript code to call the JSON using AJAX.
<div class="js-rssfeed" data-url="rss.json"></div> //HTML
//TypeScript Code
class RSSFeedManager {
"use strict";
private rootSelectionString: string = ".js-rssfeed";
private $rootSelector: JQuery;
constructor() {
var base = this;
base.$rootSelector = $(base.rootSelectionString);
base.rssValidate();
}
private rssValidate() {
var base=this;
if(base.$rootSelector.length!==0) {
//getRssFeedJson();
}
}
}
var _RSSFeedManager = new RSSFeedManager();
export = _RSSFeedManager; | using **$.getJSON** Jquery function you can load JSON data from the server using a GET HTTP request.
/////
private rssValidate() {
var base=this;
if(base.$rootSelector.length!==0) {
var jsonUrl = base.$rootSelector(base.$rootSelectionString).attr('data-url');
$.getJSON(jsonUrl, function(data) {
console.log(data);
});
}
}
}
///////
hope this help | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "ajax, json"
} |
How replace post date with event date
I need to show the event date instead of the (default) post date for each post.
How can I do this?
I tried with Event Post plugin, but I can't get the event date and put it overwriting the published post date.
I tried with a custom field too (using Advanced Custom Field plugin), but I have the same problem: I can't replace the post date with the "date picker field".
For me it's important to use the default post format of wp and not a plugin that adds item "Events" in the wp backend menu.
How can I resolve this? IMO the wp developers should include the possibility to change the date status from published to event date.
Many thanks in advance. | Ok, great. It is using the posts for concerts, parties...etc.
You need to create a plugin:
Simply, create a folder inside the /wp-content/plugins and name is /my-events-plugin
Create a new PHP file, name it my_events_plugin.php, and use the following template:
<
There is this tutorial that will get you to adding the custom field and save it:
<
Hope this gets you going :) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "date"
} |
Are there individual memory allocations for different user roles in WordPress?
I am attempting to edit a specific page via the WordPress admin area while logged in as an Editor, however, the page dies with the following error:
> Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 72 bytes) in **[PATH]** /htdocs/wp-includes/meta.php on line 841
This is only affecting this page, and granted, it is a very content heavy page, but attempting to edit the page as an Administrator works fine. Why might this be? | Because of this line in `wp-admin/admin.php`:
if ( current_user_can( 'manage_options' ) ) {
wp_raise_memory_limit( 'admin' );
}
In other words, WordPress raises the memory limit to `WP_MAX_MEMORY_LIMIT` within the admin, but only for users with the `manage_options` capability i.e. administrators.
Your best bet is to raise the default memory limit in your `wp-config.php`:
define( 'WP_MEMORY_LIMIT', '256M' ); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "user roles, post editor, memory"
} |
Locked out when attempting a migratoin
I am porting my site over to a staging server for experimentation using the duplicator plugin. Been getting a lot of strange artifacts along the way, including the password no longer working. The wp-config file was changed, so I'm thinking that this has futzed up a lot of the security keys, etc.
I attempted a pw reset and the key for that is invalid as well, failing on multiple attempts. I'm at a loss here, how do I log in? I have access to the database and all the files on the server and I am not particularly worried about meddling as this is a staging server. Any suggestions? | Copy the keys and salts from the production site?
Try updating the password with WP-CLI? | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "staging"
} |
How to hide .js files on wordpress website using php or wp plugins or any?
How to hide my script files in wordpress. I tried this idea from this blog
// include a javascript file
echo "<script type='text/javascript'>
/* All your javascript code goes here */
</script>";
I got an error like this:
Parse error: syntax error, unexpected 'echo' (T_ECHO), expecting ',' or ';' in child-2\scripts.php on line 14
The 14th line is: `document.getElementById('next-btn').disabled = false;`
The `header.php` file has: `<?php include('scripts.php'); ?>`
How can I hide my javascript files?
Any plugins or any another method to hide my script.js files on wordpress website... | You can not mix js and php. It seems (sure) that your js script (that was embed in the document), has php in it. That can work if the code is embed in the document as the php tags are open and close correctly.
If you link to a js file, there is no way for it to understand php tags, function...
If you want to add safely some php in a js file, one way is to echo the script in the document (but you don't want), other way is to enqueue the script and use wp_localize_script() to handle some php var.
If you can show some more code about `script.php` ? | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -4,
"tags": "php, functions, jquery, javascript"
} |
Conditional does not work with add_filter
I want the conditional to be applied and that it is only displayed on pages, but it does not work, what is wrong?
function luc_add_cutom_fields_to_content( $content ) {
$custom_fields = get_post_custom();
$content .= "<div class='cta-div'>";
if( isset( $custom_fields['luc_name'] ) ) {
$content .= '<h3> '. $custom_fields['luc_name'][0] . '</h3>';
}
if( isset( $custom_fields['luc_description'] ) ) {
$content .= '<p> ' . $custom_fields['luc_description'][0] . '</p>';
}
if( isset( $custom_fields['luc_action'] ) ) {
$content .= '<a href=" ' . $custom_fields['luc_link'][0] . ' ">' . $custom_fields['luc_action'][0] . '</a>';
}
$content .= '</div>';
return $content;
}
if( is_page() ) {
add_filter( 'the_content', 'luc_add_cutom_fields_to_content' );
} | `is_page()` requires `WP_Query` to be initialized and I assume your code runs before this. You can use this function within the filter callback instead:
add_filter('the_content', function($c){
return is_page() ? luc_add_cutom_fields_to_content($c) : $c;
}); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "filters, conditional content"
} |
Send email once every 12 months to a particular user
I'd like to send an email (only one) to a specific user every 12 months after a given date. Would you please provide me with the PHP code that would allow me to specify the starting date and send the email? | Set `update_user_meta()` for a `WP_User` if `get_user_meta()` ends up empty.
Update a key with a future date for the next year:
$startDate=date('Y-m-d');
$futureDate=date('Y-m-d', strtotime('+1 year', strtotime($startDate)) );
Schedule an event in one year with `wp_schedule_event()` or use `'daily'` to check all users for a relative year date.
// WP_User_Query arguments
$args = array (
'meta_query' => array(
array(
'key' => 'future_email_date',
'value' => date('Y-m-d'),
'compare' => '<=',
'type' => 'DATETIME',
),
),
);
// The User Query
$user_query = new WP_User_Query( $args );
When you find a match, use `wp_mail()` to send your email. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -2,
"tags": "email"
} |
AdBlock blocks my non-advertising sidebar images
The AdBlock add-on blocks my non-advertising images which are displayed in the sidebar of my WordPress site pages. Is there any way to stop blocking these images? Please help. | Generally AdBlock blocks common advertising image sizes like 300*250, 720*90, 125*125. Change the image size to uncommon size.
Some file names like banners, adv are also blocked. Your image will be blocked even if directory name has words like banners, adv. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -1,
"tags": "plugins, customization, wp admin"
} |
Lightweight framework
I am looking for a lightweight and fast wordpress framework to create simple 5-6 pages websites. I tried to create one myself but never had enough time. I also used premium themes but they are too heavy. I want a small understandable framework to stick to and extend its functionality with plugins, I also want to code it easily. Which framework is superfast, light and programmer-friendly. | I recommend the Genesis framework by Studiopress: <
They are widely used so there is a lot of resources available and good support on their website. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "theme development, themes, framework"
} |
Website is loading twice unnecessarily
In pingdom my dev website is loading twice. I tried googling and added and searched every option it has to offer like the following. But it's not working. I have also uninstalled some of the themes but still no success. Any help/suggestions are welcome.
Site Url: my site
Website Loads Twice Unnecessarily | Based on the result from Pingdom (< it looks like the redirects are all from your advertising providers. So you don't have much choice in how they work and there redirects. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "performance"
} |
How to hide widget if current category has no posts assigned to it?
I'm using the following code and the Widget Logic plugin to dynamically display or hide a widget on category pages:
$thiscat = get_category( get_query_var( 'cat' ) );
$parent = $thiscat->category_parent;
return
!(is_page( ) || (is_category( ) && empty ($parent) ) );
I would like to add a further condition to this that checks whether or not the current category has any posts assigned to it. If not, then don't display the widget.
I tried using `category_count;`. but couldn't get it to work. Here's the complete code I tried:
$thiscat = get_category( get_query_var( 'cat' ) );
$parent = $thiscat->category_parent;
$postcount = $thiscat->category_count;
return
!(is_page( ) || (is_category( ) && empty ($parent) && $postcount > 0 ) ); | It might be you're using the category on a custom post type, in that case `category_count` won't include those. There's another handy value on the `$category`-object however: `$category->count`. Try replacing this:
$postcount = $thiscat->category_count;
with this
$postcount = $thiscat->count;
> The count attribute includes custom post types as well if the custom post type uses standard categories.1 | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "widgets"
} |
What is the use of a custom taxonomy?
I was wondering what the use of a **custom taxonomy** is. While reading through several tutorials on how to create a **custom post type** I very often read about custom taxonomies. But I can’t really figure out what the concept behind that is, because categories can also be used in custom post types, so why use a custom taxonomy? When is it better to use custom taxonomies over categories. **Can anyone explain the concept behind custom taxonomies?** | **Taxonomy**
Essentially, a taxonomy is a way of classifying data. Typically a taxonomy will have a set of characteristics that is unique to it.
In WordPress by default it has four taxonomies, post tag, categories, link categories,Post Formats. To be obvious, if a taxonomy had the same characteristics as another data type, it wouldn’t be a different taxonomy! Example of those characteristics follow:
* **Post Tag:** acts like a label, attached to a post.
* **Category:** acts like a “bucket” in which we put posts, are often hierarchical. Posts can live in multiple categories.
* **Link Category:** acts like a label, attached to a link.
* **Post Formats:** data represent of a post and can be used by theme.
Official Documentation <
< | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "custom post types, custom taxonomy"
} |
Check if page is embeded
I'm trying to make condition that checks if the page is embeded with iFrame, but all the ways I know won't work. I'm embeding Woocommerce single product page, on custom template where only necessary scripts and styles are loaded (template is loaded depending on string query).
The problem is that, I want to change "add to cart" message only when the certain query string exists. `if(isset($_GET['embed_act'])) {}` doesn't work, and `get_permalink()` returns empty string.
Does anyone know how to check existence of query string or at least if the page is loaded in iframe? | The server doesn't know what the client is doing with the output and as such, you're limited in what you can assume. You may or may not have params sent in the request, referer, current uri and headers.
* `$_REQUEST['embed_act']`
* `$_SERVER['HTTP_REFERER']`
* `$_SERVER['REQUEST_URI']`
* `get_headers()`
On the JS side, it might be possible.
if(self==top)
{
//...
}
if( parent==top )
{
//...
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "embed, query string, iframe"
} |
WordPress Customizer Default Image
I'm trying to set a default image to a Customizer image with the code below but image does not display.
<img src="<?php echo get_theme_mod( 'header_image' , '<?php get_template_directory_uri(); ?>/images/default-image.jpg' ); ?>">
Am I missing something? | Can you try this if it will work.
<img src="<?php echo get_theme_mod( 'header_image' , get_template_directory_uri().'/images/default-image.jpg' ); ?>"> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, theme development, themes, theme customizer"
} |
Add comma between variables
I am trying to use this code to add a comma between two variables but getting 600 error:
<?php the_field('fl_venue');. ', ' .the_field('fl_address'); ?>
what's wrong? | You don't concatenate these outputs. The_field will print while get_field can be used to concat.
<?php the_field('fl_venue');
echo ', ';
the_field('fl_address'); ?> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -1,
"tags": "php, advanced custom fields"
} |
Change Custom Post Type slug
I'm working within a child theme so I don't want to edit the file that is registering a Portfolio CPT to my site. I used a plugin to change the name from Portfolio to Stories, but the plugin doesn't give an option for the slug.
I tried using the following function:
function change_slug_of_post_type_portfolio() {
register_post_type('portfolio', array('rewrite' => array ('slug' => 'stories',)));
}
add_action('init', 'change_slug_of_post_type_portfolio', 20);
But it removes Portfolio entirely from the WordPress admin sidebar. | The `register_post_type_args` filter can be used to modify post type arguments:
add_filter( 'register_post_type_args', 'wpse247328_register_post_type_args', 10, 2 );
function wpse247328_register_post_type_args( $args, $post_type ) {
if ( 'portfolio' === $post_type ) {
$args['rewrite']['slug'] = 'stories';
}
return $args;
} | stackexchange-wordpress | {
"answer_score": 31,
"question_score": 11,
"tags": "custom post types"
} |
Why does comments_open() return false when publishing a scheduled post?
My plugin does stuff whenever a post is published and comments are enabled for that post. It works fine when publishing a post as normal, but if a scheduled post is published, it doesn't.
Here's what my code looks like:
function do_stuff( $new_status, $old_status, $post ) {
global $post;
if ( !comments_open( $post->ID ) ) {
return;
}
/* do stuff */
}
add_action( 'transition_post_status', 'do_stuff', 10, 3 );
After some debugging, I was surprised to find the problem was `comments_open()` returning `FALSE`, every single time a scheduled post was published, regardless of the "Allow Comments" setting.
Why is this happening? | The problem was caused by referencing the `global $post` object. The `global $post` has not yet been initialized with the new post's details, so checking to see whether or not its comments are open will always return false at the `transition_post_status` hook.
The `$post` variable passed to my `do_stuff()` function _does_ contain all the correct information about my new post, so I work with it instead. I eventually ended up with something like the following, which functions correctly with both regular and scheduled posts:
function do_stuff( $new_status, $old_status, $post ) {
if ( $post->comment_status == 'closed' ) {
return;
}
/* do stuff */
}
add_action( 'transition_post_status', 'do_stuff', 10, 3 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development"
} |
Different template for subcategories
I would like to have a different template for categories and subcategories The categories template is set in categories.php is it somehow possible to load the subcategories template from subcategories.php or something like that? | The template hierarchy has filters for all types of templates. Here we can use `category_template`, check if the current category has a parent, and load the `subcategory.php` file in that case:
function wpd_subcategory_template( $template ) {
$cat = get_queried_object();
if ( isset( $cat ) && $cat->category_parent ) {
$template = locate_template( 'subcategory.php' );
}
return $template;
}
add_filter( 'category_template', 'wpd_subcategory_template' ); | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 4,
"tags": "categories, hierarchical, template hierarchy"
} |
Unable to find translations in WordPress theme
I am using Zerif Lite as theme for my WordPress website. It is developed for English users, but 98% of the theme settings and Customizer are translated (in french for me).
I have checked the `languages` directory looking for `.mo`, `.po` and `.pot` files but nothing related to the french translation.
I have done a research (search tool in DreamWeaver) into the whole Wordpress directory with a french string found into the theme settings, but nothing found either.
I cannot figure out how the theme is able to translate everything. Thanks for any help. | There are three usual possibilities:
1. Translation files somewhere in theme's directory.
2. Translation files in site's directory, defined by `WP_LANG_DIR` constant (typically `wp-content/languages`).
3. Theme's original strings are in different language, so that is its default state and it needs to be translated _to_ English. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "themes, translation"
} |
How do you change the tag font size in the repeater-template.php
I am very new to Wordpress and I am trying to change the font size in a custom theme from the repeater-template.php. I have the following:
<?php the_tags('<li>', '</li><li>', '</li>'); ?>
Can I simply add the font size in this way?
<font size="6"><?php the_tags('<li>', '</li><li>', '</li>'); ?></font>
Thanks for your help,
G. | In the CSS file you can easily add it.
li {
font-size: 6px;
}
Note: now the font-size of all `li` elements will be 6px
If you want only the tags `li` to be that size it's better to give them a class.
<?php the_tags('<li class="tags">', '</li><li class="tags">', '</li>'); ?>
and the CSS:
li.tags {
font-size: 6px;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, tags, html"
} |
Optimising uploads folder then re-uploading?
Rather than using a plugin to optimise images via the admin, would downloading and optimising locally work as well?
As in would downloading the uploads folder, using something like ImageOptim to optimise all the images then re-uploading them work?
Or for the site to take advanced of an optimised image does it need to be done online? | Yes, downloading the images directory (uploads) and running through those images via any optimization software would work.
Only thing that you **should** take care of is that the **images path and name** should be same as before. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "images, optimization"
} |
Get current week's day and time outside the loop
I am trying to get the current week's day and time based on WordPress time settings. So for today, I want to output `Friday` and `2:56 PM` for the time.
The `the_time('l')` and `the_date('d')` functions seems to be only working when in the loop, I could use `date('l')` but what if the php time is different than the time user sets in WordPress settings, could that happen? | Use `current_time` to output the time based on the timezone set on the blog's General Settings page. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "date, date time, timezones"
} |
How can I tell if a post has been published at least once?
I am working on a plugin that has a piece of meta data attached to each post. The fields are editable in a meta box on the post. This is all working fine.
I would like to prevent anyone from modifying the settings in meta box once the post has been published. By virtue of the application looking for this meta data, it doesn't make any sense for the meta data to change after publish.
So, is there any way to tell if a post has been published at least once? This way I can disable the controls in the meta box. | We can do this by storing the value into postmeta when post is published first time.
function save_ispublished( $post_id ) {
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return;
$published_once = get_post_meta( $post_id, 'is_published', true );
// Check if 'is_published' meta value is empty.
if ( ! empty( $published_once ) ) {
$published_once = 'yes';
}
// store is_published value when first time published.
update_post_meta( $post_id, 'is_published', $published_once );
}
add_action( 'save_post', 'save_ispublished' );
you can check it by get the meta value.
$is_published = get_post_meta( $post_id, 'is_published', true );
if( $is_published == 'yes' ) {
/*
* Actions if post is already published atleast once.
*/
}
Hope this help ! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, metabox, post meta, publish"
} |
Wordpress HTTP 500 Error
I'm getting a HTTP 500 Error on my website. Not sure what it could be. But when I refresh the page, everything works correctly. Here goes the exact error
The www.brothas.online page isn’t working
www.brothas.online is currently unable to handle this request. HTTP ERROR 500
Usually it happens when trying to login or access the back end of the website. Any help or questions would be much appreciated. Thanks | You've got an SSL certificate on the site.
So start by telling people to go to < instead of the link above ;)
More importantly:
Second go ' **Settings** ' -> ' **General** ' and set both ' **WordPress Address (URL)** ' and ' **Site Address (URL)** ' to ' **< '
Then go to ' **Settings** ' -> ' **Permalinks** ' and save you settings again.
This should fix the redirect error.
If those steps don't fix it, you may have an issue with your **.htaccess** file. Rename it and save your Permalinks again.
Here are a few popular articles for more in-dept support:
<
<
I encourage you to try my tricks before going down the rabit hole. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "500 internal error"
} |
Site Icon upload and display in a theme
Sorry for my stupid question,I am new to wordpress development.
I want to upload the site logo and icon via my theme's option page.Anyone can help me with a code snippet
Thank you! | Please find the answer here - < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "uploads, logo"
} |
Polylang not translating Metabox fields
I'm using Polylang to make my website multilingual. but when I edit a custom metabox's field in a post, the same field in the post's other language also changes to that. So that it seems that the metaboxes are only in one language! | Turn off custom fields syncronisation on polylang.
I would also then add specific code to tell polylang to copy (not sync) the metas upon translation creation (so when you click '+' it will also copy the metas, but changing the metas after this, won't sync with other translations):
add_filter('pll_copy_post_metas', 'copy_post_metas', 10, 2);
function copy_post_metas($metas, $sync){
if(!is_admin()) return false;
if($sync) return $metas;
global $current_screen;
if($current_screen->post_type == 'wine'){ // sustitute 'wine' with your post type
$keys = array_keys(get_fields($_GET['from_post'])); // an example from ACF
return array_merge($metas, $keys);
}
return $metas;
}
Reference: < | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "metabox, plugin polylang"
} |
wp_editor doesn't save styling
After editing/styling i save the post and this doesn't keep the styling instead give me plain text.
<?php
$content = get_post_meta($post->ID,'principle_duties',true);
$editor = 'principle_duties';
$settings = [
'textarea_rows' => 10,
];
wp_editor($content,$editor,$settings);
?>
//////////////////
if ( isset( $_POST['principle_duties'] ) ) {
update_post_meta( $post_id, 'principle_duties', sanitize_text_field( $_POST[ 'principle_duties' ] ) );
}
[![edited one\[1\]](

This function strips all HTML tags, so the value being stored has no HTML. That's why it's coming out as totally plain text.
To sanitize `wp_editor` I would use `wp_kses()`.
See here on how to use it: <
For the `allowed` HTML tags, you can simply pass the `global` variable `$allowedposttags` which I believe would be the same way WordPress does things with it's editor in posts/pages' content. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp editor"
} |
Loop of custom post type names
I have a lot of different custom post types like person, company, nonprofit, etc. I want to show a loop of their names but I also need to exclude some. Is there a way to give certain post types a shared label that I can then use as an argument to loop through them? | I don't think there's a way, in WP's native features, to give a post type, itself, `meta`.
You can get post types in your code using `get_post_types( $args, $output, $operator )`.
$post_types = get_post_types( $args, $output, $operator );
<
But the only way I can think of to exclude post types based on a mutual value/variable is by setting relevant `post type settings` when registering the `post type`' - e.g. `'publicly_queryable' => false`.
<
And then, you can use `get_post_types()` to find only the post types that have a particaulr value of, for example, `publicly_queryable`.
This may suffice for what you're trying to do. There is no 'post type meta` in WordPress to allow you to set a 'shared label' for the post types themselves.
If my fix above doesn't suffice, then maybe this plugin will be a good place to start (or at least look at it's code) -< | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "custom post types, loop"
} |
how to increase custom post value by one most efficiently?
I have a custom post type (created with cmb2) which always contains a number (can be zero as well).
Some times i need to increase it by one with php, so i do this:
$value = (int) get_post_meta($post->ID,'myfieldkey',true); $value++; update_post_meta($post->ID,'myfieldkey', $value);
i guess i can make it a little shorter by doing this:
$value = (int) get_post_meta($post->ID,'myfieldkey',true); update_post_meta($post->ID,'myfieldkey', ++$value);
But still it seems to me like a very long code for this simple need.
**My question is:** Is there a shorter more efficient way to the same thing? (i am doing the same thing to multiple fields at the same time sometimes so it will really help me decrease the amount of code i'm using. | Enter `WP_Post` and the "magic" getter - did you know...
$value = get_post_meta( $post->ID, 'custom_field', true );
...is the same as
$value = $post->custom_field;
So you can shorten your code to:
update_post_meta( $post->ID, 'custom_field', $post->custom_field + 1 );
Note you _cannot_ do `$post->custom_field++` \- since the property doesn't actually exist, it can't be modified. Read more about overloading in PHP. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "php, custom field, post meta"
} |
CSS Minification
Can someone help me understand the process that goes into employing CSS and JavaScript minification?
I am going to be having some development work done on my site to speed it up and I need to know how much work goes into minifying CSS so I don't get taken advantage of. | Generally very little. There are plenty of automated systems for minifying both JS and CSS, and in all likelihood your developer will use one. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "css, javascript, customization"
} |
RewriteRule accepts numbers but not letters in tag
## RewriteRule only works with numbers
I currently try to get the link
> example.com/subdir/StackExchange/
to act as a link with e.g. an additional website tag:
> example.com/subdir?website=StackExchange
* * *
I set up a RewriteRule in the .htaccess that looks as following:
RewriteRule ^subdir/(.*)/$ subdir.php?website=$1 [L]
When I use numbers (`example.com/subdir/123/`), `echo $_GET["website"]` successfully echoes "123". As soon as I use alphabetical letters (`example.com/subdir/abc/`) it does **not** work.
How do I get this changed? Is this an issue with WordPress? I have set the permalink option in the WordPress Settings Dashboard to "Post name". I tried other methods, too, but nothing has changed. | Leave `.htaccess` alone. You can use WordPress rewrite API for this.
add_action( 'init', function(){
return add_rewrite_rule(
'subdir/([^/]+)/?$', // ([^/]+) takes alphanumeric, while ([0-9]+) accepts digits
'index.php?pagename=subdir&website=$matches[1]',
'top'
);
});
add_filter('query_vars', function($v){ return array_merge(array('website'),$v); });
First make sure `subdir` is a valid page slug, in this example. After you save that code to your child theme's functions file or plugin, you can now use `get_query_var('website')` to get the `website` property rather than using `$_GET` global.
Hope that helps. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "permalinks, tags, rewrite rules, characters"
} |
How to add suggest plugin to theme?
Some templates where I installed, it showing some plugins suggest to install for support it.
How to can I suggest for user some plugins to support my theme? | TGM Plugin Activation is the most popular PHP library among WordPress theme developers to allows them to easily require or recommend plugins for your WordPress themes (and plugins).
It allows your users to install, update and even automatically activate plugins in singular or bulk fashion using native WordPress classes, functions and interfaces | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "theme development, themes"
} |
Highlight Single Page Ancestor
I have a calendar called Event Organizer that I have been customizing: < You'll notice if you click on one of the blue events you are redirected to a page that looks like: <
Right now, when someone goes to that page nothing in the navigation bar is highlighted, but I'd like the navigation item Calendar to be highlighted. I am using `wp_list_pages` to create my navigation.
I think I've seen something like this before, but I'm not sure what I'm after. Basically, the child page of the the Calendar page would highlight the main page Calendar in the navigation bar when you are on that page.
I thought that would involve styling `li.current_page_ancestor`, but that doesn't seem to do anything.
I don't know if it's easier to add this functionality for all child pages for any main navigation item (i.e. Home, About, Ministries, Calendar, Location, Contact), but that would work to.
Anyone have any ideas?
Thanks, Josh | So, I never did figure out how to do this without the plugin I mentioned. What fixed the issue was installing: wordpress.org/plugins/custom-post-type-parents. This plugin has a Settings page which allows you to choose the page that is the parent for your custom post type, then it adds the classes necessary to the `wp_list_pages` menu. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, functions, css, wp list pages"
} |
Issue with Wordpress category search
I made multiple custom search on my wordpress site to find post with category search. Like this:
<select id="category-select" name="category-select">
<option value="6">Todo</option>
<option value="7">Spain</option>
<option value="8">Europe</option>
<option value="30">Rest of the World</option>
</select>
<input type="text" id="autoc-input" name="autoc-input" autocomplete="off" placeholder="">
My form sends correctly all the parameters, for example if i search Barcelona for the category Spain i got this url:
> ?s=Barcelona&cat=7
I can't get any result from this query, but if i search just for my input or category. With this i got all the post from the category on the search page:
> ?s=cat=7
And with this all the post that contains Barcelona.
> ?s=Barcelona
I can't find the issue to get the results with more than one parameter. How can i fix this? | Wordpress search is very incomplete to do good post search. I find an answer editing search.php on the top of my template file.
$s = $_GET['s'];
$cat = $_GET['cat'];
$custom_query_args = array(
's' => $s,
'cat' => $cat,
'posts_per_page' => 11,
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish'
);
// Get current page and append to custom query parameters array
$custom_query_args['paged'] = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
// Instantiate custom query
$custom_query = new WP_Query( $custom_query_args );
// Pagination fix
$temp_query = $wp_query;
$wp_query = NULL;
$wp_query = $custom_query;
Like this i got all the results of the selected category. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, query, search"
} |
Passing variables to template parts
I have one template file `videos.php` which has the following line of code in it (aswell as a load of HTML):
`<?php get_template_part('loop', 'feed-videos' ); ?>`
inside that template part, I have the following:
<?php $video = 'video-' . $post->ID; ?>
<?php get_template_part( 'include', 'modal-video' ); ?>
I would then like to be able to use the `$video` variable inside `include-modal-video.php`.
So at the top of `include-modal-video.php` I have:
<?php global $video; ?>
Further down that file, I have `<h2>00: <?php echo $video; ?></h2>`
But I get nothing output from that line of code. All I see is the following indicator of where the value _should_ be
> 00
Can anyone see what Im doing wrong? | If you use `locate_template()` instead of `get_template_part()` you can use all variables in that script:
include(locate_template('include-modal-video.php'));
Then, `<h2>00: <?php echo $video; ?></h2>` will work.
**UPDATE:**
Since WP version 5.5, you can pass arbitrary data to `get_template_part()` for use in the template - see the other answer below from @Denis Fedorov | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 2,
"tags": "templates, variables, include, get template part, globals"
} |
How to prevent WP-CLI shell from exiting when an exception occurs?
I am using WP-CLI shell to quickly debug some code, but every time I run into a `fatal` exception (e.g. undefined constants/functions) the shell exits and I lose my shell session. Is there a way to prevent this?
wp> new DoesntExist();
Fatal error: Class 'DoesntExist' not found in phar:///usr/local/bin/wp/php/WP_CLI/REPL.php(37) : eval()'d code on line 1
Shell exits.. | This is the default behavior of WP-CLI's built-in PHP REPL. If you look at the wp shell documentation, it shows that you can also use the Boris or PsySH PHP REPLs.
The Boris REPL does not seem to be actively maintained; however the PsySH REPL has fairly recent maintenance, and it fixes the problem that you're experiencing.
The easiest way to integrate **PsySH** with **WP-CLI** is to use the wp-cli-psysh plugin:
# Make sure WP-CLI is up to date
wp cli update
# Install the plugin
wp package install [email protected]:schlessera/wp-cli-psysh.git
After installing the plugin, running **wp shell** should show you a PsySH header that's similar to this:
$ wp shell
Psy Shell v0.9.9 (PHP 7.3.1-1+ubuntu18.04.1+deb.sury.org+1 — cli) by Justin Hileman
>>> | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "wp cli"
} |
Remove "?repeat=w3tc" from any url
Some how W3 Total Cache produce on some pages this prefix "?repeat=w3tc". And I really want to remove this from my urls, but my research didn't help me.
Edit: I'm using other plugins now - The loading times are still good, I think. | I'm using the plugin again and this url var doesn't seem to appear. Yea it's very strange because I don't really change somthing - so it just seem to be a bug of the plugin. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin w3 total cache"
} |
Wrap every month posts in div
I have a code which wraps every 4 posts in div. How can I adapt it to wrap every month posts in div.
<?php
$args = array(
'post_type' => 'posts',
'posts_per_page' => -1,
'order' => 'DESC'
);
$the_query = new WP_Query($args);
if ($the_query->have_posts()) :
$counter = 0;
while ($the_query->have_posts()) : $the_query->the_post();
if ($counter % 4 == 0) :
echo $counter > 0 ? "</div>" : "";
echo "<div class='row'>";
endif;
?>
<div class="col-3">
<?php the_title(); ?>
</div>
<?php
$counter++;
endwhile;
endif;
wp_reset_postdata();
?> | $last_month = null;
while ( $the_query->have_posts() ) :
$the_query->the_post();
$the_month = get_the_time( 'Ym' ); // e.g. 201611
if ( $last_month !== $the_month ) {
if ( $last_month !== null ) {
// Close previously opened <div class="row" />
echo '</div>';
}
echo '<div class="row">';
}
$last_month = $the_month;
?>
<div class="col-3">
<?php the_title(); ?>
</div>
<?php
if ( $the_query->current_post + 1 === $the_query->post_count ) {
// Last item, always close the div
echo '</div>';
}
endwhile; | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "posts, query"
} |
Adding a number to a date
I confess... My php skills are bad.
I'm trying to show an events duration within a post in an events category. Example: Oct 11-14 But I'm having a problem adding an integer to a date then printing it in the correct format. Please see my code below:
<span class="news-item-date-day">
<?php the_time('M j');
$event_length = get_post_meta
($post->ID, 'event_length', $single = true);
if($event_length !== '') {
echo '-' . (intval(the_time('j')) + intval($event_length));
}
?>
</span>
the_time is Oct 11. The $event_length is 3. But the above code prints Oct 1111-3, not Oct 11-14.
Thanks in advance for your help. | You need `get_the_time`, not `the_time` to _get_ the date (the latter _echo_ 's the value). You also need to re-evaluate how you're trying to calculate the end date - you can't just "add" the number of days. What if the event length was 3 but the start date was the 31st?
if ( $event_length ) {
// Get the unix timestamp of the post
$post_time = get_the_time( 'U' );
// Increase the timestamp by the event length
$end_time = $post_time + $event_length * DAY_IN_SECONDS;
// Conditional date format depending on if the event ends in the same month
if ( date( 'm', $post_time ) !== date( 'm', $end_time ) )
echo date_i18n( ' - M j', $end_time );
else
echo date_i18n( ' - j', $end_time );
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, date, date time"
} |
Theme Development for WordPress Multisite Installation
I have built a lot of WordPress themes for individual clients. I am working on my first theme that will be used on a multisite installation. I want to make sure there isn't anything different I need to do knowing the theme will be used on a multisite install setup.
I did some Googling, but didn't find much. Can anyone share their tips, experience or articles that discuss the topic? | Themes don't function differently on multisite. So you can develop a theme just the way you are used to. Depending on your coding habits, you might want to do more thorough testing if the theme has many options and customization possibilities.
The risks are inherent to multisite, not particularly to theming. One mistake will affect many sites. Updating your theme will require very thorough testing indeed, for risk of breaking lots of stuff. Options cannot easily be changed anymore.
So, much depends on your personality. If you are a disciplined coder, who thinks a theme through before he acts, you can go ahead as you're used to. If you're a trial and error kind of coder, you will need to toughen up. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "theme development, multisite, themes"
} |
How to change version of .css in WordPress?
Like the title suggests, I'm not too sure how to change the version of a .css file in my theme. At the moment the .css versioning is like this:
<link rel='stylesheet' id='xxxx' href=' site css/ styles.css?ver=4.6.1' type='text/css' media='all' />
Is there a script that I need to run - where should I be looking to make the version 4.6.2 as per above? | The fourth argument, `$ver` for `wp_enqueue_style()` allows you to set the version:
wp_enqueue_style( string $handle,
string $src = false,
array $deps = array(),
string|bool|null $ver = false,
string $media = 'all' );
Per the docs:
> **$ver** (string|bool|null) (Optional) String specifying stylesheet version number, if it has one, which is added to the URL as a query string for cache busting purposes. If version is set to false, a version number is automatically added equal to current installed WordPress version. If set to null, no version is added. Default value: `false` | stackexchange-wordpress | {
"answer_score": 19,
"question_score": 15,
"tags": "css"
} |
Difference between 2 internationalization (i18n) functions __() & _e()
I'm learning from a plugin development course, and encountered two different internationalization functions:
<?php __('Newsletter Subscriber', 'ns_domain'); ?>
&
<?php _e('Title:'); ?>
I cannot find any reference information on when to use each one of these.
Can you point me in the right direction to learn more about these please? | `__()` "Retrieves the translated string from the translate() function" without echoing. `_e()` does the same thing but echos the output.
For more information, take a look at these help articles:
* Internationalization
* Localization
* **How to Internationalize Your Plugin**
* Internationalization Security | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "translation, localization"
} |
Wordpress loop multiple orderby query with Types toolset
I've created a "stores" custom post type and on the page I order it by title: `$args = array( 'post_type' => 'store','posts_per_page' => 100, 'orderby' => 'title', 'order' => "ASC" );`
I'm using the Types toolset and I've created a field for the admin to add the state in two letter form (CA, NY, TX...). I am trying to modify my loop to not only order by state, but also order by title and I'm not sure how to accomplish that. I looked around and it appears I can make the orderby parameter an array. Below it my code:
$state_code = types_render_field("state-code", array());
$args = array(
'post_type' => 'store',
'posts_per_page' => 100,
'orderby' => array(
$state_code => 'ASC',
'title' => 'ASC',
),
);
Am I able to order it in the following hierarchy?: 1) state code alphabetical order (AK, AL, AR....), then by 2) title | if you created the custom field using wp-Type then you would have to use `wpcf-state-code`
$state_code = types_render_field("state-code", array());
$args = array(
'post_type' => 'store',
'posts_per_page' => 100,
'orderby' => array( 'ASC' => 'DESC', 'meta_value' => 'ASC' )
'meta_key' => 'wpcf-state-code',
);
This should work, let me know. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, wp query"
} |
How to reduce the image size inside an icon?
The below image is a shortcode and it has a separate image.
The white Gear in the image is a separate image in size of 32*32 and the blue is a background color for it.
I just need **to minimize the gear image to smaller.**
!dfs
I need to set the icon like this: <
Checkout the fifth image on the link. | The quickest way to recude the image size will be to write some CSS.
Find the CSS class(es)/id(s) of that icon, and in your theme's style.css:
.icon-class{
width:20px;
}
If the image doesn't go smaller, then you'll need to set it's `width` or `max-width` to `100%', and make it's`height``auto` whilst you're at it.
If the image is actually an icon, then write the CSS rule accordingly.
The side-effect of doing it with CSS maybe that the image may become 'blurry', especially if it's a `png`.
In this case, you'll probably want to replace the actual image with a naturally smaller one....
In this case, you'll have to put the image in your own theme's directory and copy all the shortcode's code into your theme (to avoid overriding if the third-party shortcode ever gets updated) and change the image's path to your own image. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "shortcode, images, icon"
} |
Get current URL (permalink) without /page/{pagenum}/
How can I retrieve the current URL (whether homepage, archive, post type archive, category archive, etc) but always **without** the `/page/{pagenum}/` part if it's present? So, if the real URL is:
`example.com/category/uncategorized/`
OR
`example.com/category/uncategorized/page/2/`
then the return value will always be
`example.com/category/uncategorized/` | You can get the current URL through `home_url( $wp->request )`.
Try the example below:
global $wp;
// get current url with query string.
$current_url = home_url( $wp->request );
// get the position where '/page.. ' text start.
$pos = strpos($current_url , '/page');
// remove string from the specific postion
$finalurl = substr($current_url,0,$pos);
echo $finalurl; | stackexchange-wordpress | {
"answer_score": 13,
"question_score": 13,
"tags": "permalinks, pagination, urls"
} |
Plugin with specific admin menu icon
My new plugin uses the **default icon** set of WP in the **admin-menu**. That is not what I want.
How do I code within my **plugin** or via **functions.php** a specific admin menu icon that suites my needs for my plugin?
> Is there a tiny code script / example to use where I can define what icon/image I want?
Also do not want to use an external plugin for this. It has to be a part of my plugin.
Hope some of you can give me a good start with this. Thanks. | For **custom menu** you can use:
<?php
add_menu_page( $page_title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position );
?>
Second last option is for the **custom icon url**
Here is the reference from wordpress.org, you can read more about wordpress administration menu. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "plugin development, admin menu"
} |
Taxonomy's title
I've installed Woocomerce plugin and custom post type 'product'. There are also categories of this type named 'product_cat'. I need to display name of categories on single-product.php
I've tried in this way:
<?php $term = get_term_by( 'name', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); echo $term->name; ?>
But it's unsucessful. When I checked the type that returned to _$term_ , it displayed as boolean. | This piece of code will return all categories assigned to current product.
global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
$cat_name .= $term->name.', ';
break;
}
echo $cat_name;
> add this code inside `single-product.php`
Hope this help ! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, custom taxonomy, taxonomy"
} |
Using Excel formula in PHP. Use ^ symbol
how do i calculate this in php
(1-(1+(0.004936230552))^-((48)))
This is a formula in google excel sheet and i can't produce the same result in php. The actual answer is **0.2105005887** But when i use this in php i get this answer **5.2121761747624E+110**
i am using pow function of php This is my code
echo pow(1-(1+(0.004936230552)),-((48)));
Thank you. | This will get the answer you are looking for:
echo 1 - pow( (1+(0.004936230552)), (-48) );
That will output 0.21050058867618.
It's an order of operations issue; the spreadsheet version of the formula is subtracting from 1 last, while the PHP in the question is subtracting from 1 earlier. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "php"
} |
WP and object persistence (or lack thereof)
I read the docs for WP_Object_Cache, including the part about "if you need persistence you need to use a plugin" - like a memcache or APC based plugin.
So, for all other globals (`$post`, `$current_user`, etc.) - there is no intra-page persistence, correct?
All the uses of those globals depends on the .php files being chained in one long execution event - is that right? I'm trying to get my head around this, as it almost seems like there is application-level persistence; maybe this illusion is just a result of walking the scope tightrope very well (?)
And for user login persistence, is it simply depending on cookies? | PHP is inherently designed as non–persistent language, every request starts from no state and builds up from there.
WP mostly follows this, with every request performing core boot and proceeding to process context from GET/POST request (and possibly user cookie).
The typical mechanisms for persistence in WP are:
* database (posts / metas / options)
* object cache (transparently makes Cache API, which by default only lives within page load, to persist)
So effectively if you want something to persist you need to actively take care of storing it via appropriate WP API. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "plugin development"
} |
Multisite Network menu links not updating
I recently made a copy of my live Multisite network and moved it to a domain for testing. For some reason the links in the "Network Admin" menu are not updating to the new testing domain. These links reside under:
My Sites -> Network Admin -> Dashboard/Sites/Users etc..
I've gone through the database, htaccess files and config files but I'm not sure where the links to the old site are coming from. I can go through each site individually and browser through pages and plugins, etc but when I try to go the Network admin there is a 302 redirect to the old domain. It's very strange. | Pat J's answer is correct but left out one important step.
In wp-config.php the DOMAIN_CURRENT_SITE constant must be updated or the behavior that brandozz explains will occur.
**_When updating domains for a WordPress Multisite:_**
1. Update the DOMAIN_CURRENT_SITE constant in wp-config.php
define('DOMAIN_CURRENT_SITE', 'my-domain-name.com');
2. In DB table named "wp_sitemeta" update "siteurl" meta key
3. In DB tables named "wp_{blog_id}_options" update "siteurl" and "home" meta keys
4. Search for remaining links to update in post content with phpMyAdmin or MySQL command line. _Be careful when changing links in JSON or serialized arrays._ | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "multisite, redirect, options, wp config"
} |
How to delete attachments associated with custom field type when post property changes?
I have a WordPress site with cars that have a custom field named "deal type". That field can be either "selling" or "sold".
The "selling" cars have a custom field named "main picture", with a single picture attached to it, and another named "gallery", with multiple car photos as attachments.
When the site admin changes a "selling" car to "sold", I need to delete all those attachments associated with the gallery, in order to save space (but I must keep the attachment added in the "main picture" field).
Is there any hook to detect that the custom field "deal type" has changed to "sold" and trigger the deletion of all the attachments associated with the "gallery" custom field?
Additional information: I use the Advanced Custom Fields Pro version to create the custom fields. | You can use the `save_post` hook.
add_action( 'save_post', 'mytheme_my_post_just_updated' );
function mytheme_my_post_just_updated($post_id){
$deal_type = get_field($post_id, 'deal_type');
if($deal_type == 'sold'){
$gallery = get_field($post_id, 'gallery');// This bit and the next few lines will depend on how you've set up the custom field.
// Fast forward a few lines...
foreach($images as $image){ // I'm assuming that $images is an array of attachment_ids, but will depend on how you've used ACF to create the custom field
wp_delete_attachment($image, true); // args are attachment_id and whether or not to bypass trash.
}
}
}
Put the above code into your theme's `functions.php`.
More on `wp_delete_attachment()` \- < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom field, images, attachments, advanced custom fields"
} |
WP_Query to get post on frontpage
I've been working on my frontpage for a website, and now, at the bottom I want to add another post, outside the main loop, to this page.
I've used a WP_Query:
$args = array(
'post_type' => 'post',
'tag_id' => '32'
);
$fp_post = new WP_Query( $args );
if($fp_post->have_posts()) :
while ($fp_post->have_posts()) : $fp_post->the_post();
the_content();
endwhile;
else:
echo 'its not working';
endif;
Now, I get back that it's not working, but I'm sure there is a post with an id of 32. This should mean my array is empty, but I don't know why this is. Did I make some basic mistake somewhere? | If you're trying to get a post with the id of _32_ , the parameter you would use is `p`, which is one of the Post & Page Parameters. `tag_id` is used for querying posts with a particular Tag ID.
$args = array(
'post_type' => 'post',
'p' => 32
);
$fp_post = new WP_Query( $args );
if ( $fp_post->have_posts() ) :
while ( $fp_post->have_posts() ) : $fp_post->the_post();
the_content();
endwhile;
else:
echo 'it is not working';
endif; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query, theme development"
} |
Are WP images responsive by default?
I have learned that when upload a single image, WP will automatically create 3 copies of it as Thumbnail (150×150), Medium (300×300), Large (1024×1024) & original size.
1. does that mean if I use css to set image width, WP will automatically get the corresponding size image (that WP created) to use?
2. if I dont set any width for image (max-width: 100%), what happen when the screen is scaling smaller, does WP still automatically get corresponding size image to use?
3. is the right way means I should upload an image with the exact native size that I need to use on desktop screen and not worry anything about responsive image? | It's change automatically change image while image's in responsive mode.We can add all images here so it's cut automatically with screen size.
add_action( 'after_setup_theme', 'wpdocs_theme_setup' );
function wpdocs_theme_setup() {
add_image_size( 'category-thumb', 300 ); // 300 pixels wide (and unlimited height)
add_image_size( 'homepage-thumb', 220, 180, true ); // (cropped)
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "images, css"
} |
How to get category id of current post?
I need to get the category id of the current post outside the loop. First I get the category based on the post id:
global $wp_query;
$postcat = get_the_category( $wp_query->post->ID );
Now how to get the category id? I tried: `$cat_id = $postcat->term_id;` but it's not working. | function catName($cat_id) {
$cat_id = (int) $cat_id;
$category = &get_category($cat_id);
return $category->name;
}
function catLink($cat_id) {
$category = get_the_category();
$category_link = get_category_link($cat_id);
echo $category_link;
}
function catCustom() {
$cats = get_the_category($post->ID);
$parent = get_category($cats[1]->category_parent);
if (is_wp_error($parent)){
$cat = get_category($cats[0]);
}
else{
$cat = $parent;
}
echo '<a href="'.get_category_link($cat).'">'.$cat->name.'</a>';
}
USE `<a href="<?php catLink(1); ?>"> <?php catName(1); ?>` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 3,
"tags": "categories"
} |
How to modify query on category pages to show only sticky posts?
I'm using the following code to filter posts on category pages so only sticky posts are displayed.
add_action( 'pre_get_posts', function( \WP_Query $q ) {
if( ! is_admin() && $q->is_category() && $q->is_main_query() ) {
$sticky_posts = get_option( 'sticky_posts' );
if( ! empty( $sticky_posts ) )
$q->set( 'post__in', (array) $sticky_posts );
}
} );
?>
The problem is, if there are no sticky posts then all the category's posts are displayed. If there are no sticky posts I don't want any posts to be displayed. | Just set 'post__in' to a null array.
add_action( 'pre_get_posts', function( \WP_Query $q ) {
if( ! is_admin() && $q->is_category() && $q->is_main_query() ) {
$sticky_posts = get_option( 'sticky_posts' );
//If there are sticky posts
if( ! empty( $sticky_posts ) ) {
$q->set( 'post__in', (array) $sticky_posts );
}
//If not
else {
$q->set( 'post__in', array(0) );
}
}
} ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "sticky post"
} |
Hook action when create new category
well I need do some things when new category is created,
I've been looking for which is the hook for this but I don't found nothing that's works.
If you can help me, thanks. | The hook you want is `create_{$taxonomy}`.
E.g.
add_action('create_category', 'my_theme_do_something', 10, 2);
function my_theme_do_something($term_id, $taxonomy_term_id){
// do some things
} | stackexchange-wordpress | {
"answer_score": 5,
"question_score": -1,
"tags": "categories, taxonomy, hooks"
} |
Get plugin to background of page
Sorry for asking 2 questions in one day, but I can't figure this out and couldn't find anything on internet as well.
With wordpress I created a simple website with a sticky menu. Everything worked fine, until I started adding a google maps plugin and a photo gallery plugin. Now, if I scroll down, the output of the plugins (photo's and a map) cover my menu. (It's on this website: < \- scroll down to see what's wrong)
I added my css file properly within the functions file:
function komErbij_res() {
wp_enqueue_style('style', get_stylesheet_uri());
}
add_action('wp_enqueue_scripts', komErbij_res());
I guess this has something to do with the order of calling the stylesheets and plugins, but I don't have any idea how to solve this.
If someone could help me, you would make my day :)
Rik | Your CSS file is loading fine, yes.
But you need to add some more to it.
`z-index` is used to say where to place an element in the 'layers', when elements overlap.
The higher the `z-index` the higher it will appear.
add `z-index:10` to the header:
header.site-header{
position: fixed;
top: 0;
margin: 0px;
width: 100%;
background-color: rgba(0,0,0, 0.6);
color: white;
z-index: 10; /* New style */
}
In your case, a `z-index` of `1` will do it, though. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, theme development, css"
} |
How to change the order of the Front Page so it doesn't appear first
I have a Portal page and also a Home page. The Portal page is very basic and has a handful of links linking to different systems, one of the links leads to the Home page of WordPress. I want the Portal page to be listed as #1 in the navigation and the Home page (Front page) to be listed as #2. Wordpress seems to ignore the Order field in the page options if the page is designated as the Front Page (designated via Settings --> Reading --> Front page displays --> Static Page).
Is there a way to have a page other than the front page in the order position #1 in the navigation? | Thank you @WebElaine for the tips about using a child theme. I found the code that put the `Home` link first. The file was located in `/wp-content/themes/vantage/inc` and file `extras.php`
function vantage_page_menu_args( $args ) {
$args['show_home'] = false;
return $args;
}
Had to change `$args['show_home'] = false;` to `false`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "pages, navigation, order"
} |
Update modified Shopify third-party theme
I bought a Shopify third-party theme and I have added some script changes for customization and functionalities.
What is the best practice to update a modified Shopify third-party theme without losing the previous changes and breaking my website? | Modifying third-party themes should be avoided in the first place. Creating a child theme is the proper way to customize a third-party theme because it allows for the parent theme to be updated without worrying about having your customizations overwritten when updating. Being able to update is important for security and it's nice to be able to have the latest features and bug fixes.
Since the Shopify theme has already been modified, here are the steps that you can take to get a child theme up and running and update your parent theme.
1. Make a backup copy of your modified parent theme and set it aside for safe keeping.
2. Create a basic child theme using the documentation for the modified third-party theme and activate it.
3. Port your modifications over to the child theme.
4. Replace the modified Shopify theme with the newly updated version.
5. Test to ensure that everything is working properly. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, themes, child theme, updates, e commerce"
} |
Can the_post_navigation() be outside of the loop?
I am wondering if `the_post_navigation()` function will work properly outside the loop in single views.
For example:
while ( have_posts() ) : the_post();
get_template_part( 'template-parts/content', 'single' );
endwhile;
the_post_navigation(); | Yes, `the_post_navigation()` works outside of the loop on single post views.
Following the function calls, `the_post_navigation()` uses `get_the_post_navigation()` which uses `get_previous_post_link()` and `get_next_post_link()` which use `get_adjacent_post_link()` which finally uses `get_post()` which defaults to the global `$post` object.
Here's an excerpt of `get_adjacent_post_link()`:
function get_adjacent_post_link( $format, $link, $in_same_term = false,
$excluded_terms = '', $previous = true, $taxonomy = 'category' ) {
if ( $previous && is_attachment() )
$post = get_post( get_post()->post_parent );
else
$post = get_adjacent_post( $in_same_term, $excluded_terms, $previous, $taxonomy );
if ( ! $post ) {
$output = '';
} else {
$title = $post->post_title;
... | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, loop, themes, navigation"
} |
add onchange to select in a wp form
I am using wp_dropdown_categories to create a dropdown in the frontend. It creates a nice dropdown select. Now I would like to add `onchange="myFunc()"` to the `<select>`. I need this to trigger some js function when someone selects specific option.
I also took a look into another relevant codex link, could not figure it out. Is there a native wordpress way of doing this ? If not, can you suggest me a solution. I mean something like this.
<select id="my_cats" class="postform" name="my_cats" onchange="myFunc()"> | you can add any attribute to `<select>` using wordpress filter `wp_dropdown_cats` . `wp_dropdown_cats` filter allows you to modify the content of the taxonomy drop-down output. Try below code.
function addAttributeToDropdown($html_content){
$html_content = str_replace('<select','<select onchange="myFunc()"',$html_content);
return $html_content;
}
add_filter('wp_dropdown_cats','addAttributeToDropdown');
add this inside your `functions.php` file | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, javascript, select"
} |
I want different post-thumbnail size depending on media size
I've got the following code on my home page
<?php echo '<img class="img-responsive" src="',
wp_get_attachment_image_src( get_post_thumbnail_id(), 'Large' )[0], '">'; ?>
The large size in this case is 1920x245. This works fine in a browser but when the image scales down on smaller screens it's too thin for my taste. I would like to use an image with a different aspect ratio in that scenario.
How do I adjust the above php code to be responsive to media size? | As so often happens (with my questions anyway!) the answer is simple. I added a min-height parameter of 85 pixels to the styling for the image and it crops the image once it gets to that height. Exactly the behavior I wanted.
.img-responsive{
display:block;
max-width: 100%;
height:auto;
min-height: 85px;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, theme development"
} |
Which User Role for Custom Post Type Menu - wp_nav
I have a site with a custom post type "Streams". I would like for my editor to be able to add steam post types to the main menu of the site, but he cannot see them under Appearance->Menus.
Which user role is associated with custom post type menu items (wp_nav not the dashboard menu).?
Thanks! | My first guess would be that he needs to make sure the checkbox is checked for that particular CPT under Screen Options (top right of Appearance -> Menus). | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "custom post types, menus, user roles"
} |
Is it safe to delete uploaded photos if Photon (Jetpack) is activated?
I turned on Photon (Jetpack). Now, my photos are served from Wordpress's CDN. Is safe to delete the photos I uploaded (which are stored in `wp-content/uploads/...`) ? | Even if the CDN images are cached "forever", I would not recommend deleting them from your upload folder.
You might later decide to deactivate JetPack because:
* you want to use another CDN and you only use JetPack for the Photon service.
* it somehow becomes incompatible to your later setup
* or because of possible temporary bugs in JetPack.
Not all of your images might be served by the CDN, e.g. attached ones but not used and also images that are not in posts or pages.
Reusing images in your posts or pages becomes harder, without the use of the Media library.
An edge case could be that if the site would somehow violate the terms of the service, then it could be suspended from it. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "uploads, plugin jetpack"
} |
Sanitize the output of the_title() or the_title_attribute() to remove whitespace
I have an issue. I have a piece of sharing code which I created for social media.
<a href=" the_title(); ?>.<?php the_permalink();?>" class="twitter">
Now when I run this through the W3 Validator it says there shouldn't be a space. Now when I looked at the code it was outputting the title DOES have spaces in it.
How do I sanitize this title to add in dashes within my url?
I just want the title to add dashes in this context only. I have looked at the sanitize_title function and the_title_attribute function in the Wordpress Codex but don't really know how to make it work in this situation. I am sure there is a simple solution. Any help would be great.
Dan | You can replace the space to dashes using wordpress `sanitize_title_with_dashes` function Try below code.
<a href=" echo sanitize_title_with_dashes(get_the_title(get_the_ID())); ?>.<?php get_the_permalink(get_the_ID());?>" class="twitter">
I have used `get_the_title()` and `get_the_content()` functions because these both function return the context instead of echo them, and i think you are concatenating the string.
Hope this help . | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "title"
} |
Admin dashboard does not show WordPress network sites
How do I fix that the admin panel show the sites that are in the WordPress network?
) {
echo "Hide Image";
}
else {
echo "Show Image";
}
?>
that I got from the WordPress conditional tags page. | if ( get_the_ID() !== 45 ) {
// Will run for all posts other than ID 45
}
if ( get_the_title() !== 'My Post' ) {
// Will run for all posts that don't have the title "My Post"
}
if ( get_post_field( 'post_name' ) !== 'my-post' ) {
// Will run for all posts that don't have the slug "my-post"
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, categories, conditional tags"
} |
Shortcode is not processed when added to option field using wp_editor
I managed to add a button to TinyMCE with this code:
wp_editor( get_option('piedino_plugin_var_testo'), 'piedino_plugin_var_testo_id', array(
'wpautop' => false,
'media_buttons' => false,
'textarea_name' => 'piedino_plugin_var_testo',
'textarea_rows' => 10,
'quicktags'=>false
) );
I get the content of the `wp_editor()` with this:
get_option('piedino_plugin_var_testo');
If I use a shortcode in this `wp_editor()`, when I display the content in the front end, the shortcode doesn’t work; I see `[shortcode]` instead the result of the shortcode
Any suggestions? | WordPress applies various filters to the content before it is output. The filter `do_shortcode` is the one that processes shortcodes. You can apply all of the same filters to the output of your editor by using the following code:
echo apply_filters( 'the_content', get_option( 'piedino_plugin_var_testo' ) );
Here is the list of all of the filters applied to `the_content`:
add_filter( 'the_content', 'capital_P_dangit', 11 );
add_filter( 'the_content', 'wptexturize' );
add_filter( 'the_content', 'convert_smilies', 20 );
add_filter( 'the_content', 'wpautop' );
add_filter( 'the_content', 'shortcode_unautop' );
add_filter( 'the_content', 'prepend_attachment' );
add_filter( 'the_content', 'wp_make_content_images_responsive' );
add_filter( 'the_content', 'do_shortcode', 11 ); // AFTER wpautop() | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "shortcode, wp editor"
} |
Uncaught TypeError: jQuery is not a function
I'm getting a strange jQuery error message in my theme. The message is showing in browser console-
> Uncaught TypeError: jQuery is not a function
Note: I used the bellow method in my custom jQuery files and I set `jquery` in the dependency parameter when I enqueue my custom JS files.
(function($) {
"use strict";
// jQuery code goes here
})(jQuery);
var $mcj = jQuery.noConflict(true);
Where is the problem? | I solved the problem my own. I just deleted the last line-
var $mcj = jQuery.noConflict(true);
from my jQuery file then I get rid of the Uncaught TypeError. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "jquery, errors"
} |
Add filter button to custom post type in admin area
We use a 3rd party custom post type for events in which they have removed the ability to filter the posts.
 {
var d=new Date();
var h=d.getHours();
var m=d.getMinutes();
var s=d.getSeconds();
h = h % 12;
h= h ? h : 12; // the hour '0' should be '12'
var ampm=h >= 12 ? 'PM' : 'AM';
m = m < 10 ? '0'+m : m;
s = s <10 ? '0'+s: s;
m = checkTime(m);
s = checkTime(s);
document.getElementById('timeis').innerHTML =" "+h+":"+m+":"+s;
}
function checkTime(i) {
var j = i;
if (i < 10) {
j = "0" + i;
}
return j;
}
setInterval(function() {
startTime();
}, 500); | Here's an updated version of the code which fixes the extra zero caused by the redundant time checks in `startTime()`:
**JavaScript**
function startTime() {
var d=new Date();
var h=d.getHours();
var m=d.getMinutes();
var s=d.getSeconds();
h = h % 12;
h = h ? h : 12; // the hour '0' should be '12'
var ampm = h >= 12 ? 'PM' : 'AM';
m = checkTime(m);
s = checkTime(s);
document.getElementById('timeis').innerHTML =" "+h+":"+m+":"+s;
}
function checkTime(i) {
if ( i == 0 ) {
return "00";
}
if ( i < 10 ) {
i = "0" + i;
}
return i;
}
setInterval(function() {
startTime();
}, 500);
**HTML**
<a id="timeis" href="#"></a> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "javascript"
} |
PHP error with a shortcode: "no suitable wrapper" for file_get_contents
Why do I get the PHP warning "no suitable wrapper" for file_get_contents in this shortcode? It's probably more a PHP issue than WordPress.
The shortcode works fine and outputs in a page/post. But my error log is filling up with the warnings. I know PHP warnings are not serious, but I still want to fix the code that throws the warning.
// Wikipedia Last Edit Date
function wikipedia_article_date() {
$url = "
$data = json_decode(file_get_contents($url), true);
$date = $data['query']['pages']['746140638']['revisions'][0]['timestamp'];
$date = new DateTime($date);
return $date->format('m-d-Y');
}
add_shortcode('article_date','wikipedia_article_date'); | Use the HTTP API:
$http = wp_remote_get( ' );
if ( ! $body = wp_remote_retrieve_body( $http ) )
return;
if ( ! $data = json_decode( $body, true ) )
return;
$date = new DateTime( $data['query']['pages']['746140638']['revisions'][0]['timestamp'] );
return $date->format( 'm-d-Y' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, shortcode, json"
} |
Can I create (or update) user password with WP-CLI by hash?
I want to make a user-create snippet, but it must not includes plain password.
$ wp user create username [email protected] --role=administrator --user_pass=password
So can I create (or update) user password by hashed value? | There is not "one command" in Wordpress CLI that does the job: <
However using other commands, you can overide the user password directly in the database using the following:
USER_ID=$(wp user list --login="$USR_LOGIN" --format=ids)
wp db query "UPDATE wp_users SET user_pass='$HASHED_PASS' WHERE ID = $USER_ID;"
First line is optional if you already know the user ID.
To hash a password, use the following:
wp eval "echo wp_hash_password('$CLEAR_PASSWORD');" | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "wp cli"
} |
Remove the link to a featured image if and only if it's not a gif
I have a condition whereby:
if( has_post_thumbnail() ){
return get_the_post_thumbnail();
}
However, I would like that condition to be valid for all images's extensions, except for `.gif`.
How can I achieve that?
My ultimate goal is not to be taken to the article when the featured image on the home is `.gif`. | If you want to check the _mime type_ of the _featured image_ , then one way could be to use `get_post_thumbnail_id()` to get it's ID and then check the mime type with `get_post_mime_type()` :
if( has_post_thumbnail() && 'image/gif' !== get_post_mime_type( get_post_thumbnail_id() ) {
return get_the_post_thumbnail();
}
where you return it for non-gifs. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "post thumbnails"
} |
frontend upload return async-ajax.php 302
Recently we moved a site to SSL following popular guidelines.
Everything worked as expected except when it comes to uploading images via the frontend.
Trying to upload an image we get the following response:
302 POST async-ajax.php 200 GET
So image upload fails, cookie is invalidated (reauth=1), user is forced to login again.
Other observations:
1. Users are able to upload images via backend
2. There is no errors in wp-debug
3. It works fine if we revert to non-ssl | If you are using custom front-end registration through `wp_signon` function, check, if the second parameter, passed to that function is true:
$user_signon = wp_signon( $info, true ); ).
The second parameter tells WordPress to set the secure cookie for login. It works fine with SSL. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "uploads, ssl"
} |
How does Wordpress interpret the php code?
I decided to create my own wordpress theme. Before i begin i wanted to know how Wordpress interprets PHP code. For example:
**1)** On **functions.php** , some themes start with wordpress features, some start with styles and scripts, some start to define folder patchs etc...
Is there any standard on how to list on the right way? How does WordPress understand it, does they load all code first and then they list it based on function priority number?
Any suggestion? | `functions.php` file of a theme gets `include`ed by WP as any PHP file, there is no special processing or anything.
So the code in the file just runs and what happens happens.
It is considered proper practice in WP that any code that doesn't _need_ to run immediately on boot should be instead hooked to appropriate point in load. Typically that is `init` (where core/plugins/themes load is considered mostly complete) and later hooks. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php"
} |
1 Database for multiple WordPress themes
I am the owner of a small company that makes wordpress websites for entrepeneurs. When we go to a customer, we want to show some examples of themes we could be going to use. We want the themes to display some information of the customer, like a logo. a header title and some personal information. We will probably be adding this information through the Customizer of the theme(s).
This will result in 3 different themes with identical information.
We can make 3 different databases and change `the wp-config.php` file to the right database name when we want to show a different theme, but we were wondering if there was another solution?
We only have 1 domain available, so it's not possible to put each theme on a different domain.. | If you're going to be visiting clients to show them your templates I would personally recommend installing Wordpress on your local computer by following the instructions on the below page.
<
Once you have installed Wordpress locally you could make a backup of your live Wordpress site and restore it on your local computer by following this guide.
<
Doing it this way you're not limited by your hosting providers 1 site only policy. You can also make modification without it affecting your live website in any way. You'll also avoid the embarrasing moment of not knowing whether it's a clients internet connection that's slow or the server the website sits on. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "themes, database"
} |
XML file import for attachments or featured images
I'm hoping there is a direct tag for bringing in featured images/attachments with XML post imports, using an external url?
Explanation: I am successfully importing a large number of custom posts by way of XML files and the standard WordPress Importer. (The posts are from a non-WordPress proprietary CMS).
The one thing that isn't working is the featured image. I'd like to be able to import the featured image/thumbnail attachment within the XMl file, using the external url for the image. Is this possible without a plugin? Is it possible to do this as a tag for an attachment?
In other words, is there a tag for the post/item that would work, such as:
`<tagname> </tagname>` ? | I'm not aware of the way this could be done with a WXR file alone; after all attachments are posts, and if you're importing images from elsewhere you'd need to do all the WordPress processing on them to make them into posts (from WordPress's point of view).
You may get inspired with how this plugin performs the import.
> ...uses FileReader and to parse the XML file in the browser, then uses ajax to request WordPress perform individual uploads. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "import, xml"
} |
How to change the menu mark up with walker_nav_menu class?
I want to remove the `< ul >`,`< li >` tags and add a `< span >` tag inside the `< a >` tag.
<nav class="menu">
<div class="menu-list">
<a data-scroll="" href="#" class="">
<span>Home</span>
</a>
</div>
</nav>
Any help or explanation is appreciated.
This is where I am right now
class Walker_Nav_primary extends Walker_Nav_Menu
{
function start_lvl( &$output)
{ // ul
$indent = str_repeat( &output, $depth );
}
function start_el(argument)
{ // anything inside ul - opening tags
# code...
}
function end_el(argument)
{ // anything inside ul - closing tags
# code...
}
function end_lvl(argument)
{ // close ul
# code...
}
} | I just posted an answer to this here: How to create this custom menu walker?
Basically, you want your `start_el` and `end_el` to looks something like this:
function start_el(&$output, $item, $depth=0, $args=array()) {
$output .= '<a href="#"><span>' . esc_attr($item->label);
}
function end_el(&$output, $item, $depth=0, $args=array()) {
$output .= '</span></a>';
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "menus, walker"
} |
Replace Dashes Before Title in Page List
I want to replace the dashes before the page title in the dashboard page list. For each hierarchy below the first, a dash is prepended (as seen in the screenshot below):
;
function change_my_title( $title ) {
return str_replace( '–', $title );
// nor preg_replace or – or — work
}
**So my question is:** How can I replace these dashes with something specific? Do I really have to implement a custom list table or meddle around with jQuery? | You can't change dashes using any filter because there is no filter available to change it.
but still you can change this using jQuery put this code inside functions.php
add_action('admin_head',function(){
global $pagenow;
// check current page.
if( $pagenow == 'edit.php' ){ ?>
<script>
jQuery(function($){
var post_title = $('.wp-list-table').find('a.row-title');
$.each(post_title,function(index,em){
var text = $(em).html();
// Replace all dashes to *
$(em).html(text.replace(/—/g ,'*'));
});
});
</script>
<?php
}
});
See < | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 4,
"tags": "pages, filters, jquery, hooks, wp list table"
} |
Wordpress Redirect: Default Password Reset URL
I would like to redirect the default wordpress password reset url /end-point. So the url before the password is reset.
/wp-login.php?action=lostpassword
redirect to /password-reset/ (which is aalready setup)
I have created a custom page, so any user querying the old url will be redirected to the new page. | There is a filter to change the lost password url. Try this :
add_filter( 'lostpassword_url', 'my_lostpassword_url', 10, 0 );
function my_lostpassword_url() {
return site_url('/password-reset/');
}
**Note** : You can place code in functions.php or make plugin (Recommended). | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "php, functions"
} |
Multiple Google Analytics codes for individual pages
I've seen a couple of posts on here with the same subject but none matching what I'd like to do.
My site has a Google Analytics code for the whole main site - say `www.example.com`
There are 2 pages on the site that Id like to individually monitor and I have a GA code for each page - let's say `/page1` and `/page1/page2`
Is it possible in Wordpress for GA to monitor:
* GA code 1 - whole website but exclude `/page1` and `/page2`
* GA code 2 - just the page at `www.example.com/page1`
* GA code 3 - just the page at `www.example.com/page1/page2` | Sure, that's possible. Are you including the GA-code anywhere on your site today? If not, you can add the following code to your theme's functions.php-file:
add_action('wp_head', 'add_google_analytics');
function add_google_analytics(){
global $post;
if (is_page('page1')){ ?>
<!-- Analytics code #1 -->
<?php } else if (is_page('page2')) { ?>
<!-- Analytics code #2 -->
<?php } else { ?>
<!-- Analytics code #3 -->
<?php }
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "google analytics"
} |
Can we hook the Customizer on a post or page on the front of the site?
If you go theme shopping on various company sites like < you will notice that within many demos, there is a pull out feature that allows you to change the look and feel of that particular theme page (i.e. dark version / light version).
This inspired me to ask the question if the customizer (or anything similar to it) can be loaded on the front end, on a specific post or page, so that front end users can do similar things like change colors (obviously something I will have to code in), but hopefully you get the idea. If I wanted to show case several themes I built for a client, I would want them to have the ability to do a "customizer experience" without accessing the dashboard area.
Is this possible? Is it already built? or do I have to rebuild something like this up from scratch? Or can I hook into something to pull out the customizer to the front end? I have no idea where to start. | This question is a bit too broad for a Q&A model, but I tend to think that everything you need is already built in. Except that you will want your clients to login, something you can have them do on the front end.
You could even make a custom role which will allow you to hide the whole admin bar from them except for the button that lets them open the theme customizer.
In the theme customizer you can change the capability on settings, which will make some of them available for users with low clearance. In this way you can prevent them accessing settings they have no business with.
You can use the active callback on sections to load different sections for different types of pages (front, archive, singular, and so on).
If you don't want them to save their actions, hide the save button. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "user roles, theme customizer"
} |
500 error when using wp_upload_dir()
I'm using wp_upload_dir() within my plugin directory so that I can create a folder if it doesn't exist before uploading images to the directory. And for some reason it gives a 500 error during my ajax call.
my code looks like this
<?php
$upload_dir = wp_upload_dir();
$user_dir_name = $upload_dir['basedir'].'/mg_gallery';
if( ! file_exists( $user_dir_name ) ) {
if ( wp_mkdir_p( $user_dir_name ) ) {
$is_successful = true;
} else {
$error_msg = "Sorry Couldn't create directory. ";
$is_successful = false;
}
} | This was occurring because I wasn't using wp's built in ajax. | stackexchange-wordpress | {
"answer_score": -2,
"question_score": 0,
"tags": "php"
} |
Warning: Illegal offset type in /var/www/html/wp-includes/option.php on line 1924
I just updated to the latest WordPress Version 4.7
And now I get this error in the admin menu:
`Warning: Illegal offset type in /var/www/html/wp-includes/option.php on line 1924`
The strange this is that the file has only 1689 lines of code. What error can this be? | I had these exact errors. I updated all the themes and de-activated all my plugins, then re-activated them one by one. Eventually all plugins were reactivated and the errors are gone. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, errors"
} |
Notice: _usort_terms_by_ID is deprecated since version 4.7.0! Use wp_list_sort instead
I have updated my **wordpress** version from **4.6.1** to **4.7.0** , but after updating i am getting this error message, when i add or edit any product in **woocommerce** :
> Notice: _usort_terms_by_ID is deprecated since version 4.7.0! Use wp_list_sort instead. in /wp-includes/functions.php on line 3783
But after searching whole files there is no function like that, so how i can fix this issue.. | The function `wp_list_sort()` has been introduced in WordPress 4.7. It wasn't available before. That's probably why your plugin isn't using it.
The function `_usort_terms_by_ID()` is still working, and it is actually much faster than `wp_list_sort()`. Which makes it hard to understand why it has been deprecated. _But_ in your own code keep in mind that functions starting with an undercore (`_`) are meant to be private in WordPress. You should not use them in your code, at least not directly.
The real issue here is that you can see notices. These are _informal_ , they should be visible for you only, not for your visitors. If that site is public, make sure you turn the debug mode off in your `wp-config.php`.
WooCommerce has a fix already; you will get that with the next update, so just keep your site up to date, and you are fine. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 4,
"tags": "plugin development"
} |
SELinux security vs Wordpress updates
We have a quite huge Wordpress multi-sites installation with **lots of themes/plugins**. So we often have new available updates (core/themes/plugins).
We don't use **automatic updates** :
* `AUTOMATIC_UPDATER_DISABLED` is `true`
* `DISALLOW_FILES_MODS` is `false`
Indeed we use a security system on server side (Security-Enhanced Linux) that **prevent file modification**. We have to do the updates manually, by first disabling SELinux, then starting the updates, then enabling SELinux back...
Is there any way we can **enable auto updates** and then :
2. detect when an update process is going to start, then disabling SELinux
3. detect when the update process is done, then enabling SELinux back
4. log to file or database what has been updated
I have identified the file _wp-includes/update.php_ but I want to avoid modifying core files. | No.
First there is the practical problem of enabling your OS being influenced by the web server, something that should never be possible. (a plugin will trigger an update and make you open to all attacks)
Second, on a more philosophical level, what is the point of hardening your security if in the end you let any script being installed on your system without any minimal audit.
Security is many times not convenient... If you have nothing of value to protect then you don't need the SELinux layer, otherwise I can't imagine how justify relaxing your security for even a minute just to save few hours of work a month.
.... In addition, you should always test new versions of plugins and themes before deploying them to production and never ever use unsupervised automatic updates. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "multisite, security, updates, linux, automatic updates"
} |
I Have No List Of Blogs - Empty Blog Folder Recreating Itself
I have a main website <
And then I have individual blog posts such as the slug of i-was-a-web-developer at the same address (not allowed to post more than two links).
However I have no front-page for the blog itself, listing all the blogs. < just takes me to a directory structure.
I believe it is caused by a folder called “blog” in my file structure. If I delete it, I can then see my blog temporarily, until I do anything such as pressing refresh.
The empty folder then quickly recreates itself.
Can anyone kindly advise what I may have done wrong!
Thanks James | Finally worked it out - I noticed that the upload path was wrongly set that is why a folder called blog appeared. I've changed that and deleted the blog folder. All is working. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "blog"
} |
Wordpress Admin Post Type Table Class Filter Hook
So I've looked all through the documentation to see if I can find a filter hook of some sort to add an extra class name to the Wordpress/WooCommerce (CPT) post table in the backend. There must be a way somewhere, as WooCommerce adds on "status-wc-" into the html class.
Anyone able to help me out and point me in the right direction?
` is used to generate these classes. You can filter `post_class` to change the output.
Example
is_admin() && add_filter( 'post_class', function( $classes, $class, $post_id ) {
$post = get_post( $post_id );
// Decide whether to add a class or not …
$classes[] = 'my-custom-class';
return $classes;
}, 10, 3 ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "plugin development"
} |
Not display post meta if empty
Im in need for some help. I have a seconds to min converter I want to not display if value is either 0 of if there was no meta value inputed. I realized the it outputs "0 MIN'even if no meta value was inputed I want that to not happen.
Here's the code
<strong>
<?php
$duration_in_seconds = get_post_meta( get_the_ID(), 'wpscript_duration', true );
$minutes = floor($duration_in_seconds / 60);
$seconds = $duration_in_seconds - (60 * $minutes);
echo $minutes;
echo " MIN";
?>
</strong> | Use in this way-
<strong>
<?php
$duration_in_seconds = get_post_meta( get_the_ID(), 'wpscript_duration', true );
if( '' != $duration_in_seconds && 0 != $duration_in_seconds ) {
$minutes = floor($duration_in_seconds / 60);
$seconds = $duration_in_seconds - (60 * $minutes);
echo $minutes;
echo " MIN";
}
?>
</strong> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts"
} |
WP 4.7 broke get_post_type or requires an explicit integer value?
I just upgraded to WP 4.7, and suddenly code that uses get_post_type($id) stopped returning anything, and didn't throw an error either.
After trying a few things, I found that it would start working again if I changed my code from
get_post_type($id)
to
get_post_type(intval($id))
But I can't find anything in the docs about WP suddenly requiring explicit integer values. Anyone else seeing this?
**UPDATE**
So, using trim instead of intval works too.
get_post_type(trim($id))
And checking $id `(preg_match('/\s/',$id))` shows that it had a space. But oddly, this worked just fine in WP 4.6, so something must have changed to make that less forgiving in WP 4.7 | According to the devs at WP (<
"This was an intentional change to get_post() in 4.7 - passing an invalid parameter may have previously returned a result, but it could've been an incorrect resource, for example, a value being cast to a numeric 1 and fetching from the incorrect post. get_post( 123 ) is the same as get_post( '123' ) but not the same as get_post( " 123 " ) (Which now fails) IMHO, so I agree with the change, especially in this case."
So I would consider this the definitive answer. The behavior has changed to something better, it was just a surprise that it worked before. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom post types"
} |
Deleting images in array
Is it possible to delete all the images with ID's given in input field?
I have field:
<input type="hidden" id="deleteimg" value="3008,3009,3010,3011,3012" class="something">
I'm getting field on POST:
$todelete = SOMEimp::request( 'deleteimg' ) );
Then I wanted to get all the values with:
$imgarray = explode(',', $var);
I was trying with:
wp_delete_attachment( $imgarray, true)
But it doesn't accept arrays I guess or for some other reason it doesn't work. Am I doing something wrong? | **wp_delete_attachment** not support array, this function support integer value only, so you have to perform this function inside loop.
<?php
$imgarray = explode(',', $var);
for($i = 0; $i < sizeof($imgarray); $i++) {
wp_delete_attachment( $imgarray[$i], true);
}
?> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "functions, forms, attachments"
} |
how to search all user meta data that have value like "vivek"
I want to search all users metadata that have meta value like " **vivek** " if the mata key are " **submitted** " and the meta value store in a serialized format
$args = array(
'meta_query' => array(
array(
'key' => 'submitted',
'value' => 'vivek',
'compare' => 'LIKE'
)
)
);
$query = new WP_User_Query( $args ); | As you said data is stored inside meta_value as serialized format. You can match your string among the serialized string like data.
$args = array(
'meta_query' => array(
array(
'key' => 'submitted',
'value' => sprintf(':"%s";', 'vivek'),
'compare' => 'LIKE'
)
)
);
$query = new WP_User_Query( $args );
Hope this help! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "meta query, user meta, json"
} |
Adding link for logged in user?
<?php if ( is_user_logged_in() ) { '<a class="btn" href="/author/<?php global $current_user;
get_currentuserinfo();
echo $current_user->display_name;
?>">Channel</a>'; } else { echo 'Welcome, visitor!'; } ?>
Anyone knows how to fix this function I wanna put in header? | <?php
if ( is_user_logged_in() ) {
$current_user = wp_get_current_user();
echo '<a class="btn" href="/author/' .
$current_user->display_name .
'">Channel</a>';
} else {
echo 'Welcome, visitor!';
}
?>
Note that `get_currentuserinfo()` is **deprecated** in favour of `wp_get_current_user()`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, php"
} |
Wordpress database products structure
I am writing an external program on c++ which supposed to import products to WordPress database (it should directly connect to remote MySQL server and just execute some SQL queries to create a new product). I have all the products' properties and remote database access, but I can't completely understand how does actually WordPress serves and orders all of it in it's database. Technology is too hard for me to understand by simply walking through the real working WP database, filled in with products :c. I also haven't found any documentations or schemes on internet.
There is only very useful db scheme of relationships between different WordPress tables, but it doesn't actually describe how is the information stored in inside.
I am new (from technical side) to that CMS, so, the final question is, which tables should be affected by my program to create a new product in WP database?
Relying upon your help. | To add product, you need to add
* an entry in posts table, with `post_type='product'`, `post_title='product_name'`, `post_excerpt='product_description'`. This will give you the post ID.
* with the post ID, you will be able to add meta datas in the `post_metas` table._product_type, _visibility, _price, _sale_price....
* use terms tables to add category related to the product
You can see all product metas (with get_post_meta() ) to learn more about all the needed one and their real names.
Ok, you want to do it with sql request, but you can also import products with a csv file or with the woocommerce Api, functions, class and dedicated method can make it easier to define the right sql request.
Hope it gives you some hints. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "database, taxonomy, import"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.