INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Change plugin's has_archive = true to false?
When a plugin registers a post type and sets `has_archive` to `true`, is there a way to change it to be false? I don't want the plugin's post type to have an archive, but can't figure out how to turn it off.
A similar questions was asked here, but has no responses: Changing a custom post type "has_archive" after registered | The `register_post_type_args` filter (available from WordPress v4.4 on) will allow post type registration arguments to be changed:
function wpse206329_custom_post_type_args( $args, $post_type ) {
if ( $post_type === "my_post_type" ) {
$args['rewrite'] = false;
}
return $args;
}
add_filter( 'register_post_type_args', 'wpse206329_custom_post_type_args', 20, 2 ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom post types, plugins, archives"
} |
Updating user meta
I'm struggling to figure out to get the code to update a single current user meta. For instance if I want to update their first name automatically. I'm using
$current_user = wp_get_current_user();
to call the current user data rather than specifying a particular user ID. | One of two functions you'll need; `update_user_meta` or `add_user_meta` \- more often than not you'll just need the former, but it's worth noting the difference:
> `add_post_meta` will only create an entry if the `$unique` parameter is false, or if there is **no** existing data for `$meta_key`. `update_post_meta` will add if no data exists yet, otherwise it will update, depending on if/what you specified for `$prev_value`.
Both functions take the same three initial parameters; a user ID, a meta key, and a value:
$current_user = wp_get_current_user();
$current_user->ID; // The current user ID
$current_user_id = get_current_user_id(); // Alternative for getting current user ID
// Update current user's first name
update_user_meta( $current_user_id, 'first_name', 'Jimbo' );
// Update a specific user's first name
update_user_meta( 4 /* User ID 4 */, 'first_name', 'Janey' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "users, user meta"
} |
How to make mailing queue using php's mail() function
I have a site running WordPress 4.3.1 and a hosts mail() limit of 14 mails per 5 minutes (Which is 2 mails per minute) and cron limit of min 5 minutes, and I am running everyone can register, Profile Builder with mail confirmation and WP Mail Bank to set wp_mail() to php's mail() function. What i need is to limit my mail queue and stimm use mail().
Thanks in forwards!!
P.S. I also have iThemes security with file change notifications. | You can write your own `wp_mail` function that will override the core one and in your own function you can enqueque emails, and then dequeue them and send them with wp-crom events. Managing the queue is not trivial but should be doable.
But the easier path is to use an external service that has an API like mailchimp. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp mail, cron, phpmailer"
} |
How to display the user's comment status on the front end
How can I display the current status of a user's comment/s (on the front end), that is, "approved" or "pending" | Displaying comment status is quite standard in every theme; maybe you have not been notice it but you have seen it for sure. All default themes do it and the default `wp_list_comments()` function does it also and it is the most common function used to display posts comments.
So, if you use default `wp_list_comments()`, you are displaying comment status already; if you are using a custom callback, you can check the comment status, for example like this:
<?php
if ( '0' == $comment->comment_approved ) {
?>
<p class="comment-awaiting-moderation"><?php _e( 'Your comment is awaiting moderation.' ); ?></p>
<?php
}
Or more accurately, you can use `wp_get_comment_status()` function:
// Return 'deleted', 'approved', 'unapproved', 'spam' or false on failure
$status = wp_get_comment_status( $comment_id ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "comments, front end"
} |
I can't upload a new wordpress theme from a zipped file
I'm having trouble trying to upload a zip file Wordpress theme that I bought from Themeforest. I'm getting an inactive "upload theme" button, I have tried to reinstall the Wordpress theme three times now, but I'm having the same problem. I also tried uploaded the theme through FTP to "content" folder, but this did not solve my problem. This started when I upgraded to Wordpress 4.3.1. I'm I missing something here? please advice.
;
I am using nginx, so every answers using .htaccess are not useful for my case. How can I solve my problem ? | I figured out how to fix my problem.
In my nginx config file (`/etc/nginx/nginx.conf`) I added `client_max_body_size 100m;` at the end of the `#Basic Settings` in the `http {}` section.
I hope this answer will help some of you and please tell me if there is any better solution to this problem. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 2,
"tags": "php, uploads, media, media library, nginx"
} |
Referencing files in JavaScript in WordPress Plugin
I have a JavaScript file in my plugin in which I need to reference a sound file to play when any link is clicked in any front end page.
I did it like this:
my_plugin/my_plugin.php
function pr_add_link_sound () {
wp_register_script('add_sound', plugins_url('add_sound.js', __FILE__), ['jquery'], '', true);
wp_enqueue_script('add_sound');
}
add_action('wp_enqueue_scripts', 'pr_add_link_sound');
my_plugin/add_sound.js
(function($){
var sound = new Audio('sound.mp3');
$('a').on('click', function(){
sound.play();
});
})(jQuery);
I added the 'sound.mp3' file in the root folder of my plugin like this:
my_plugin/sound.mp3
But the reference of the sound file in the js script is incorrect. How should I refer to the file correctly? | Use `wp_localize_script`.
function pr_add_link_sound () {
//Register the script first
wp_register_script('add_sound', plugins_url( 'add_sound.js', __FILE__ ), array('jquery'), '', true);
//Localize the sound file url to use in the script
$args = array(
'sound1' => plugins_url( 'sound.mp3', __FILE__ ),
);
wp_localize_script( 'add_sound', 'PRSound', $args );
//Enqueue the script
wp_enqueue_script('add_sound');
}
You can reference the sound in the js file like this..
(function($){
var sound = new Audio( PRSound.sound1 );
$('a').on('click', function(){
sound.play();
});
})(jQuery); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, javascript"
} |
Multi domain, multi sites with different themes and content
I have about 300 domains I need to setup wordpress. Then for each of them, I need different theme, and content of the sites will be different as well.
I have seen plugins and wordpress as network.
Some of them install the new instance in a subfolder, some in new subdomain.
What I am interested is in domain level. ie:
foo.com
bar.com
I want to have a single installation and manage `foo.com` and `bar.com` in the same instance for simplicity, authentication and management.
is there a plugin to do this? or an easy way.
I am using Go-daddy VPS that gives me CPanel. | A WordPress multi-site will handle this easily. This is what drives WordPress.com and the millions of sites (and domains) hosted there.
Each site in a multi-site can use it's own theme, will host separate content, etc. Whether you use the subdomain or subfolder install, you will need to use domain mapping to route foo.com and bar.com properly.
The most common plugin I see used for this is MU Domain Mapping: <
There are a few things notably different between WP single and WP multi. Several good posts on the WP Codex cover the details. < | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "plugins, multisite"
} |
How to get all featured image sizes and their URLs?
Is there a standard way to get all the registered sizes of the featured images? One can register different sizes with `add_image_size()`. What I need, is to get all the sizes of a featured image of a post. Something like this:
$sizes = get_post_feature_image_sizes($postid);
...which will return an array of objects like this (here in JSON format):
[
{width: 200, height: 300, url: '
{width: 300, height: 400, url: '
]
Is there anything like this, or I will have to scan all the upload folder file names with regex? | I don't remember a function that will do precisely that, but it is easily achieved with API overall:
1. Retrieve attachment ID with `get_post_thumbnail_id()`
2. Retrieve available sizes with `get_intermediate_image_sizes()`
3. For each size use `wp_get_attachment_image_src()`, which gives precisely data you need (URL and dimensions). | stackexchange-wordpress | {
"answer_score": 16,
"question_score": 13,
"tags": "post thumbnails, images"
} |
Display 4 chronological posts starting with a random post
I know that I can display 4 random posts by doing something like:
get_posts('orderby=rand&numberposts=4');
What I'm trying to achieve is starting with a random item, but then showing the next 3 posts that are in chronological order.
I'm thinking something along the lines of this:
$posts = get_posts('orderby=rand&numberposts=1');
foreach($posts as $post) {
the_title();
//get next 3 chronological posts and loop
}
I guess I need to use something like the 'offset' parameter, but with a post id instead of a position? | For a random offset we might try:
$ppp = 4;
$total = wp_count_posts()->publish;
$offset = $total < $ppp ? 0 : rand( 0, $total - $ppp );
$posts = get_posts( [
'posts_per_page' => $ppp,
'offset' => $offset
] );
## Example:
Let's take `$ppp` as 4 and assume `$total` is 6.
Then are three possibilities for the `$offset`, namely 0, 1 and 2:
Nr Offset Selections
1 0 x
2 1 x x
3 2 x x x
4 3 x x x
5 4 x x
6 5 x
so
$offset = $total < $ppp ? 0 : rand( 0, $total - $ppp );
would give:
$offset = rand( 0, 6 - 4 );
or just
$offset = rand( 0, 2 ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "php, functions, get posts"
} |
Three variables on conditional tags
I'm trying to return $ad_code if three variables are present, but it doesn't allow the third variable I'm trying to add. I want to exclude a category.
I am trying to use (in accordance with WordPress' "conditional tags")
if ( is_single() && ! is_category( '1293' ) && ! is_admin() ) {
return prefix_insert_after_paragraph( $ad_code, 2, $content );
}
return $content;
The code (including the code that specifies what $ad_code is) works. Just when I try to add in `&& ! is_category( '1293' )` it still displays on all posts (not just 1293). I tried using the category name as well, but that also did the same thing.
The third variables I've tried either stop `$ad_code` from loading on all or on no posts. | Your conditional, `is_category()` is wrong here. `is_category()` checks whether or not you are actually on a category page. By using the `!` operator in conjuction with `is_category()` and ID `1293`, this part of the condition will always return true except when you are actually on the category page for category `1293`.
If you need to exclude a certain set of posts from the category `1293`, you should use the conditional check, `in_category()` or `has_category()` ( _in essence, they both are excatly the same_ ). So your conditional statement should look something like this:
if ( is_single() // Make sure we are on a single page
&& ! in_category( '1293' ) // Make sure the post does not belong to category 1293
&& ! is_admin() // Make sure this is not an admin page
) {
return prefix_insert_after_paragraph( $ad_code, 2, $content );
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "conditional tags"
} |
Get_template_part seems to be ignoring my template
I am developing a website that requires specific pages to have certain elements change color in addition to a full-width calendar page. I figured that using page templates and changing what `get_template_part` looks for would be the simplest approach, but I've run into unexpected trouble. The page template loads fine, but the specific content template appears to get ignored, with WordPress instead loading the general template. I'm using a child theme derived from Twenty Fifteen, but this shouldn't be a problem, since the customized content template loads just fine.
get_template_part( 'content', 'page', 'kahvilaravintola' );
It should be loading `content-page-kahvilaravintola.php`, located right in the child theme's folder, but instead loads `content-page.php`, located in the same folder. I can't seem to figure out what is wrong. | Taken from the Codex and Dev Hubs:
>
> <?php get_template_part( $slug ); ?>
>
> <?php get_template_part( $slug, $name ); ?>
>
`get_template_part` only takes 2 parameters, not 3. If you look in your error log you should be seeing warnings and notices that you passed a third parameter to a function that only takes 2. I would expect your call to load the file `content-page.php` then `content.php`. Nothing is done with `kahvilaravintola`, as it's an unexpected and unused third parameter | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "page template, get template part"
} |
How to identify which javascript is being executed
I am trying to figure out which script is being called and executed within my Wordpress website.
I have website with a number of scripts that are included by the core, the theme and the numerous plugins i have installed.
This is not just for one site but on all sites I manage - I usually install w3 total cache to minify the scripts which works great BUT there are always 1-2 elements on site that stop working if their scripts are minified.
I can turn off minify to make it work again and I can exclude scripts from minification BUT I have no idea which script is listening to the functions that are failing. Removing scripts one by one is really time consuming and with the added "caching" of total cache, I can never properly identify the actual script accurately?
Is there anyway I can monitor a click on an element on page that can alert me to which javascript code is being executed from which file? | I realised through other discussions that in Chrome Element Inspector - I can put a "Break" on elements for Subtree modifications, Attributes modifications and Node Removal.
I did this for the that was calling js and then I stepped through the break to find the js code i was looking for. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, cache, plugin w3 total cache"
} |
Why BuddyPress fields not saving?
I have a Wordpress+BuddyPress site. I added some extra fields in user profile. When i registering user i fill all fields on register form. After i do redirection in user profile:
function auto_login_new_user( $user_id ) {
wp_set_current_user($user_id);
wp_set_auth_cookie($user_id);
global $current_user;
get_currentuserinfo();
wp_redirect( home_url() . '/members/' . $current_user->user_login . '/profile/edit/group/1/' );
exit();
}
add_action( 'user_register', 'auto_login_new_user' );
?>
And see that BuddyPress's fields is empty. Only default wordpress fields filled.
If i not do redirecting (i mean after registretion use a actiovation email to activate user) all fields in user profile are filling.
Any advises? | The `user_register` hook probably fires too early.
Try:
add_action( 'bp_core_signup_user', 'auto_login_new_user', 100, 1 );
`$user_id` is passed by the `bp_core_signup_user` hook. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, buddypress"
} |
How to add and clear custom post types and taxonomies in a plugin? Considerations for existing data
How do we manage the creation/deletion of custom post types and taxonomies in a plugin?
For example, if I write a plugin that creates a new custom post type and an associated custom taxonomy, what is the best practice when this plugin is removed from the system?
I would like to delete/de-register the custom post type and taxonomy and delete all the content.
How should I do this? | Custom post types and taxonomies can be registered using `register_post_type()` and `register_taxonomy()`. These functions do not actually create any data in the database. Data _is_ added when users populate content (posts and taxonomies).
When a plugin is disabled, any post types and taxonomies that it registers will be unregistered, but all of their data in the database will remain in place.
If you are going to remove data from the database, you should make it abundantly clear to the user what is happening. One common pattern is to require the user to click an option that states that they want data to be deleted when _deleting_ the plugin. The data deletion process can be run using the `register_uninstall_hook()` or `uninstall.php` file. Data should not be removed when simply deactivating a plugin. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, plugin development, custom taxonomy"
} |
query_posts works while get_posts doesn't
I try to create a page that shows my posts (a page different than the "posts page" defined in wp-admin).
When I copy my `index.php` into this new page and add
<?php query_posts('post_type=post&posts_per_page=5&paged='.get_query_var('paged')); ?>
above the
<?php if ( have_posts() ) : ?>
...
...
then everything works fine - my posts are shown. If I try to put
<?php get_posts(); ?>
instead of
<?php query_posts('post_type=post&posts_per_page=5&paged='.get_query_var('paged')); ?>
the posts are not showing.
Since everyone suggests that `get_posts()` is preferable in general over `query_posts()`, I wonder how can I have the posts showing, using `get_posts()`. | The thing is that, contrary to popular belief, `pre_get_posts` does not work for single Page requests.1 Not even for is_front_page().
As for `get posts()`, in order to work I needed to use a syntax like:
<?php global $post;
$myposts = get_posts();
foreach( $myposts as $post ) : setup_postdata($post); ?>
...
<?php endforeach;
wp_reset_postdata(); ?>
instead of
<?php get_posts(); while ( have_posts() ) : the_post(); ?>
... | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "query posts, get posts"
} |
Display post_meta-by_key on product catalogue
I'm trying to display a custom field in my woocommerce bookshop catalogue. I have added the field " **author** " and I want to display it after the product title, and before the price.
<
I think I've worked out that the place I need to display the author name is **_woocommerce_after_shop_loop_item** ,_ and I think I need to use this:
`echo get_post_meta_by_key( 'author' );`
But I'm not sure how to put it all together in my child theme's **functions.php**. This is as far as I got, but I am in need of help.
add_action( 'woocommerce_after_shop_loop_item', 'display_author' );
function display_author() {
echo get_post_meta_by_key( 'author' );
}
I'm getting an error: Fatal error: Call to undefined function get_post_meta_by_key() | That's because `get_post_meta_by_key()` isn't a WordPress function.
What you're likely looking for is `get_post_meta()`:
add_action( 'woocommerce_after_shop_loop_item', 'display_author' );
function display_author() {
global $post;
echo get_post_meta( $post->ID, 'author', true );
}
Not tested, because I don't have a WooCommerce install handy (and WooCommerce specifics are off-topic here anyway) but this is pretty standard so it should just work for you.
The `true` as the third parameter is so that `get_post_meta()` returns a string, ready to echo directly out. Without `true`, it will return an array instead (see the docs for further info). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "functions, woocommerce offtopic, post meta"
} |
What content to use for inserting images
I would like to create a page template that will have two containers. Left one should be for text (it is a multilingual website so that is why I need a page template), and the right side should be for images which are the same for all languages. My question is, what do I have to create so a client can insert and edit images as he pleases? Do I have to create a post, a page or something else? It must not be indexed as itself. I am interested in "the right Wordpress way"
<div class="col-md-6">
<?php the_content(); ?>
</div>
<div class="col-md-6">
<?php // include images ?>
</div> | Images (and other media) in WordPress are stores as attachments — which are a special native post type (more or less).
There are two common ways to display attachments in a post context:
1. Include them in post content (individually or via gallery shortcode)
2. Select one as featured image (aka post thumbnail) and have theme with support of the feature display it separately from content
So unfortunately natively there isn't a way to select _multiple_ images with intent of displaying them separately from content.
However it is a common feature in custom fields frameworks. They often offer nifty interface options for it and store attachments IDs in post's meta data, from where it can be retrieved and used.
Personally I favor Meta Box, but there are literally dozens of alternatives floating around. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "page template, content"
} |
Using URL variables on a custom WP_Query
# Background
I have a page with a custom template 'listen', with a custom wp_query running on it...
$custom_query_args = array(
'post_type' => 'post',
'tax_query' => array(
array(
'taxonomy' => 'post_format',
'field' => 'slug',
'terms' => array( 'post-format-audio' ),
),
),
);
# The Problem
When I try and filter the posts on this page with url variables ( _example.com/listen/?category_name=thebigshow_ ), nothing changes, even if I spell the category name incorrectly.
How can I use this method to filter the 'listen' page, by 'category_name' (show name)?
Thanks, Andy. | WordPress doesn't handle this logic qutomatically so you will have do do it manually.
What you need to do is:
1. Read the url parameter with get_query_var( 'category_name' );
2. injects it in your custom WP_Query:
$custom_query_args = array(
'post_type' => 'post',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'post_format',
'field' => 'slug',
'terms' => array( 'post-format-audio' ),
),
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => get_query_var( 'category_name' ),
)
)
);
Note that if you decide to pass an arbitrary variable instead of category_name, you will need to declare it before using it.
See < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query, query, urls, page template"
} |
Replacing Images in Media Library
I have a media library containing 500 images. I need to make some modifications to these images in Photoshop (batch resizing and color correction). I'm looking for a way to simply overwrite the files in the 'wp-content/uploads' directory without having to re-upload them via the media library. The file names will stay the same. I also want to be able to retain the title, alt, caption and description associated with the old image files.
What would be the most efficient way of going about this? | Well, I think the easiest way would be the following:
* Download your `wp-content/uploads/` folder so you have all images on your hard disk
* Remove the images WordPress has automatically generated (the ones with -*x*.jpg, maybe read this if you have SSH access as a filename)
* Optimize your base images with Photoshop
* Reupload the images into the `wp-content/uploads/` folder
* Use a plugin like "Regenerate Thumbnails" (I use that one often) to rebuild all the necessary images
This should work, but I have not tested it.
**Important!** Do not change the filenames of your base-images, otherwise WordPress will not find them after reuploading. _(Yeah, seems obvious, mentioned it just for clarification...)_ | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "uploads, media library"
} |
WP_Query | 'post_type' doesn't work
I'm new to WP theme development and I've an issue.
I've created a custom post type 'portfolio' via CPT UI plug-in. Now I want to create a custom query to show all the posts with the post_type = 'portfolio'. Here is my code
<div class="row">
<?php
$args = array (
'post-type' => 'portfolio'
);
$the_query = new WP_Query( $args );
?>
<?php if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<div class="col-sm-3 portfolio-piece">
<h3><?php the_title(); ?></h3>
</div>
<?php endwhile; endif; ?>
</div>
Somehow it shows me the only one post 'Hello World!' with the post_type = 'post'. By the way, I don't even have this post.
Thank you! | You have 'post-type' in code instead of 'post_type' | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom post types, wp query, loop, custom post type archives, post type"
} |
How do I check if the user is a site owner in a network?
I was accidentally using `is_admin()` to check if a user was an admin and found out that function is not checking that. So I looked for another one and I found `is_super_admin()` but that checks if you are a admin of a network of sites or owner of a single WordPress install. I have a network site and I want to know if the user is the owner of the blog. I do not want to use roles. I want to check if the user is the owner of the blog. | I have had similar issues with this in the past, WordPress really does need a `is_user_admin()` function.
In the meantime I think the best way to do this is to test if the user has certain capabilities.
function is_user_admin(){
if(!is_super_admin() && current_user_can('activate_plugins'){
// User is an admin
}
}
Reference:
* Administrator roles
* `current_user_can()` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "multisite, admin, network admin"
} |
Problem in wp_localize_script
I am try to enque and localize my word-press scripts My code for for enque my scripts is
function load_my_scripts() {
wp_register_script('custom-js', get_stylesheet_directory_uri() . '/js/custom.js', array('jquery'));
wp_enqueue_script('twentyfifteen-custom-js', get_template_directory_uri() . '/js/custom.js', array(), '20141010', true);
wp_localize_script( 'custom-js', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action('wp_enqueue_scripts', 'load_my_scripts');
My custom js is being enqueue if i do view source but not able to localize ajax.php.
Where i am making mistake please let me know. | First of all, you are NOT enqueuing the script.. Try this code, working in my test install.
function load_my_scripts() {
// Create the localizations array
$localize = array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
);
// Register The Script First
wp_register_script('custom-js', get_stylesheet_directory_uri() . '/js/custom.js', array('jquery'));
wp_enqueue_script('twentyfifteen-custom-js', get_template_directory_uri() . '/js/custom.js', array(), '20141010', true);
// Register the localization
wp_localize_script( 'custom-js', 'MyAjax', $localize );
// Enqueue the script
wp_enqueue_script( 'custom-js' );
}
add_action('wp_enqueue_scripts', 'load_my_scripts'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp enqueue script, wp localize script"
} |
Custom Fields with get_post()
I am using get_post() to call a single Wordpress post using it's post ID. I have successfully managed to pull the content / title of the post but would like to also pull custom fields also.
The code below is how I declare custom fields in a standard wp_query:
$customField = (get_post_meta($post->ID, "_mcf_customField", true));
And my get_post code below:
$my_id = 401491;
$post_id = get_post($my_id);
$customField = get_post_meta($post_id, "_mcf_customField", true); // I do not think this is correct
$content = $post_id ->post_content;
echo $content;
echo $customField; // No output
I believe the customField variable above is declared incorrectly, cannot seem to find anything in the Codex that sheds any light though. Does anyone have experience using Custom fields with get_post? | You already know the ID, so just use it:
$customField = get_post_meta($my_id, "_mcf_customField", true);
But only for reference, if you want to get the ID from the object:
$customField = get_post_meta($post_id->ID, "_mcf_customField", true); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom field, get post"
} |
Get product details by url key in Wordpress woocommerce
I want to load products deatails on my custom page.Is there any way that i can use the `url key` like ` this url `samsung-1` is the key for that product.I want to use this and get product details like name,description and attributes.Can i do this using `url key` or i have to use id for this.thanks I tried this code but this uses id :
<?php $post = get_post('5653'); //assuming $id has been initialized
echo "<pre/>";
print_r($post);
wp_reset_postdata();?> | You simply can use the existing function `get_page_by_path()` for this, which has a third parameter `$post_type` you can specify. In your case a post from the custom post type `product` is what you want.
Basic example:
$product_obj = get_page_by_path( $slug, OBJECT, 'product' ); | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 3,
"tags": "woocommerce offtopic, customization"
} |
problem migrating files from https to http mock site - how to see mock site
I used a migration/backup plugin to grab the files from a secured site to my mock up site that is not secured. Since I'm not using it for anything other than adding some functionality to it - no members, no sales of products, I didn't think of any trouble going from https to http but now I get the old
> SSL connection error ERR_SSL_PROTOCOL_ERROR message.
All the files are on the site.
What files do I need to edit so I can see the site?
Thanks. | Since you cannot get access to the website due to a HTTP/HTTPS conflict, you need to ensures that all of the URLs for your website are up-to-date, try the following steps using the Search Replace DB tool:
1. Go and download Interconnect IT's Database Search & Replace Script here
2. Unzip the file and drop the folder in your **localhost** where your WordPress is installed (the root) and rename the folder to **`replace`** (screenshot)
3. Navigate to the new folder you created in your browser (ex: ` and you will see the search/replace tool
4. It should be pretty self-explanatory up to this point: enter your old URL in the **`search for…`** field and the new URL in the **`replace with…`** field
You can click the _dry run_ button under _actions_ to see what it will be replacing before you execute the script. Once you're done be sure to remove the `/replace/` folder. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 3,
"tags": "migration, https"
} |
Is there a way to get attachment data?
So, I'm no big fan of how WP stores images (image data) and I was hoping there had been made some improvements in version 4.x. But alas no.
When I say image data, I mean `url, title, caption, alt text, description` data that you can update in the media gallery.
`wp_get_attachment_image` only returns a URL with this data
`wp_get_attachment_image_src` only returns url
`get_attached_media( 'image' )` returns some data:
public 'post_content' => string 'This is the description'
public 'post_title' => string 'This is the title'
public 'post_excerpt' => string 'This is the caption'
public 'guid' => string '
After I removed the attachment (and deleted the image), then attached another image, `get_attached_media( 'image' )` returns empty.
So **IS** there any good way of getting image data? | Don't forget that attachments are just _posts_ (though they are native posts and those tend to be a special case).
Thus simply `get_post()` on attachment ID should get you typical post object for it. :) Similarly all API functions that work on posts should work on attachments. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 3,
"tags": "images, attachments, media"
} |
Dynamically creating content on custom URL without getting 404
My goal is to have this link structure:
mypage.com/item/subitem/code
Code are 6 random letters and numbers.
I tried with having category and subcategory, but I dislike that because then i have to create post for every code that i have, and there are lots of it.
What I want to is to have a template for page item/subitem/code and just take code as query (similar to ?code) but I cannot change this structure since it's about qr codes and they cannot be changed.
Is this somehow possible? | Yes, it´s totally possible, I just did that for a similar project some weeks ago.
I found this very helpful: How to pass extra variables in URL with Wordpress
Basically the process is the following: Register new `query_vars`, fill them with life, pass them to a specific template which looks for them and then do whatever you like.
I did an integration for a REST-based web service with that. Live querying the information from the service, based on the ID I pass like this: `mysite.com/events/1567612313/`
Works fine. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, custom taxonomy, 404 error"
} |
How to set custom homepage via a plugin
I am developing a plugin movie database plugin and i want set few custom templates to wordpress theme using the plugin. how can I achieve this? | You can replace the homepage template via plugin like this:
// Filter to replace the template of the home page
add_filter( 'template_include', 'replace_home_page' );
function replace_home_page( $template ) {
if ( is_front_page() ) {
return plugin_dir_path( __FILE__ ) . 'new_template.php';
}
return $template;
}
src/read more | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, templates"
} |
how to remove or disable woocommerce order review in checkout page?
In the checkout page, there is a review order table on the bottom. I want to remove the order review in checkout page. What is the remove action ? | Just add following code into your funtions.php
add_filter( ‘woocommerce_product_tabs’, ‘sb_woo_remove_reviews_tab’, 98);
function sb_woo_remove_reviews_tab($tabs) {
unset($tabs[‘reviews’]);
return $tabs;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "woocommerce offtopic"
} |
How do I put woocommerce cart page to my checkout page?
I want my cart page to show up on my checkout page. And I want to remove the order review from checkout page. so my cart page will show on the top. | To remove order review from checkout page...
In your plugin folder Go To woocommerce->includes->wc-template-functions.php Now press ctrl+f and write woocommerce_order_review and press enter. You will find a function of the same name. Just remove its body(portion that comes under{}) And its done.
To show cart page and checkout page on sigle custom page
you can use shortcode _[woocommerce_cart]_ for cart and _[woocommerce_checkout]_ for checkout on a custom page.Use both shortcode on a single page that might do the trick. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": -1,
"tags": "woocommerce offtopic"
} |
Completely reload style.css
I have inherited a site, and I'm trying to add new styles to the style.css
Things I have tried that have NOT worked
* Reload browser cache
* delete WP Super Cache cache
* Disabled WP Super Cache plugin completely
* add !important to my styles
* removed 'Version:' from css comment at the top of style.css
* edited style.css ditrectly from Appearance > Editor rather than push via ftp
* many combinations of all of these
I notice in the web inspector that all styles are coming from style.css:1 (line 1) which makes me thing there is a css minification going on somewhere
Is there an default cache somewhere to clear via GUI?
Is there a css cache file I can delete from the server?
Any other ideas? | Using the Network tool in the Inspector I found out that there was a third party caching service in action. "Cloudflare" via Bluehost. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "cache, css, plugin wp supercache"
} |
Wordpress s2 member plugin not working
I had use the s2 member plugin for registration.When i register it as new member it shows password where send by email but i cant get any mail upon registration please anyone help me | You must be using the plugin on local server. If you wants to receive e-mails after registration then first you have to upload your website on internet. Because any plugin that use to send email, doesn't work in local server. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "plugins, plugin development, user registration"
} |
Use html tags in shortcode_atts, is it real?
can i use html tags in shortcode attributes? like this:
function b_text( $atts, $content = null ) {
extract( shortcode_atts( array(
'text' => '<div class="myClass">DOM</div>'
), $atts ) );
ob_start();
?>
<div>
<div> <?php echo $text; ?></div>
</div>
<?php
$content = ob_get_contents();
ob_end_clean();
return $content;
}
add_shortcode('b-text', 'b_text');
Probably i can use some actions or filters to redefine my html content in atts? it is at all possible? thanks! | While it is a technically possibility, it's most likely direction that isn't worth it.
Overuse of shortcodes for what is essentially (crappy) templating is problematic and has a history of security issues.
In recent months there has been ongoing planning and discussion about possibility of changes to shortocde syntax and mechanics in core. HTML in attributes is explicitly named as one of the problems that led to it. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, shortcode"
} |
How to add attributes to WordPress Admin Sub Menu List Items
I have been trying to find a way to add a class or an id to my custom administration sub menu. I only see a class on the first menu item. I would either like to add a css class or an ID on my sub menu list items. | So I found a solution to my problem. I just added a `span` tag in the add_submenu_page() hook and it work:
add_submenu_page(
# The slug for the parent menu page to which this sub menu belongs
'email-service',
# The text that't rendered in the browser title bar
'Breaking News Email',
# The text to be rendered in the menu
'<span class="breaking-news-toggle">Breaking News Email</span>',
# the capability required to access this menu item
'send_email',
# The slug by which this sub menu is identified
'my-email-service',
# the function used to display the options for this menu's page
array(&$this, 'email_service_form')
); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "filters, wp admin, admin menu"
} |
Posts in Admin only display 1 Post instead of all
When I run wp-admin/edit.php I normally should get a list of all Posts.
WordPress 4.3.1 running Avada Child theme.
But I only get the last Post in the list.
All (8) | Published (7) | Draft (1)
As you can see there are 8 in total and 7 Published.
Has someone an idea how to get all Posts in the list? | Number of items per page was set to 1! Problem solved | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 0,
"tags": "posts, admin"
} |
Hide posts with meta key in WP_Query
I was reading this post to "Exclude posts with specific meta_value" but it does not work correctly. Here is the arguments I am passing to `WP_Query` :
$args=array(
'cat' => $catid,
'category__in'=> $term_ids,
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'featured_post',
'value' => 'on',
),
),
);
Using the above method, I can list posts which use meta key, but I do not want posts, with meta key "featured_post" to be displayed. If I change the `value` to something else then no post is displayed.
The meta value is simply a check box for featured posts. | Use `compare` with `NOT EXISTS` to get posts without that meta key.
'meta_query' => array(
array(
'key' => 'featured_post',
'compare' => 'NOT EXISTS',
),
) | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "wp query, post meta"
} |
Change WooCommerce add_to_cart Button Text?
I am trying to change the add_to_cart button text for all products based on category. For category 'course' with ID 330, I would like the button to read 'Register'.
For all other products, I would like it to read 'Buy Now'.
Here is what I have thus far in my functions.php:
add_filter( 'woocommerce_product_single_add_to_cart_text', 'custom_cat_add_to_cart_text' );
function custom_cat_add_to_cart_text( $default ) {
global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
if ( array_key_exists( 330, $terms ) ) {
return __( 'Register', 'course' );
} else {
return $default;
}
}
This is failing to change the button text. | It's not working because:
get_the_terms( $post->ID, 'product_cat' )
yields an array of objects, to test against those objects you have to run a loop and pull a $term_id property out of each object.
Wordpress to the rescue! Wordpress has a helper method for that...
has_term(330,'product_cat', $post);
Use the has_term method to satisfy your conditional. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, woocommerce offtopic, e commerce"
} |
Is there a wildcard/catchall filter hook?
I would like to filter all the options values, but the option filters are option specific. Is there a way I could do something like
add_filter('pre_option_*', 'my_check');
? | I've tried the same thing and was able to hook into the `pre_option_` filter by using `all` as filter.
add_filter('all', 'pre_option_',1,3);
function pre_option_($actionHook,$bool=false,$option_name)
{
if(strpos($actionHook,'pre_option_') === FALSE){
return $bool;
}
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "filters, options"
} |
Global variables during plugin activation , deactivation and uninstall operarations
For activation hooks codex states that you have to be explicit on globals:
A note on variables during activation
But that seems not to be working on uninstall.php
If i define a global in my main plugin file like this:
global $plugin_options_name;
$plugin_options_name = 'xxxxxxxxx';
Activation hook can use it via global statement , whereas uninstall.php cannot.
I have to redeclare the variable inside unistall.php
If this is the case, if i switch to uninstallation hook this will change? | You should prefer the uninstall hook over the file if your main plugin doesn't have side effects (outputs html or writes to file/DB automatically when loaded). IMO there is too much risk (i.e. non zero) of doing the uninstall.php code wrong and open the file to direct execution from the outside. This also help in having all the relevant code in one place.
uninstall.php, when exists, is being executed without loading the plugin code (that is the whole point of it) and therefor whatever is declared in the plugin code will not be available to uninstall.php. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, variables, uninstallation"
} |
1px black line appearing down right side of thumbnails (theme snaps)
For some reason on most of the thumbnails there is a black 1px line to the right of the image.
This looks to be a cropping issue or something but there is a 1px thick line on the right hand side of a lot of my thubnails.
I am unsure why this is as all the thumbnail images are the same size. You can see the page at <
Any help would be very much appreciated. | For some reason, I think the image does not take all available space that it has, you can add a `width: 100%;` on the `.post-thumbnail img`. It solves the issue here.
Edit: You can see, by looking at the chrome dev tools (or firefox/IE) that the container does not have the save width as it children :
;
Change locale like this:
$my_plugin_domain = 'my_plugin_domain_name';
$override_locale = 'es-ES';
add_filter('plugin_locale',
function ($locale, $domain) use ($my_plugin_domain, $override_locale) {
if($domain == $my_plugin_domain) {
$locale = $override_locale;
}
return $locale;
}, 10, 2); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, plugin development, localization, language"
} |
Redirecting category link to first child post
I am trying to redirect the category link to the first child post. I am using following code in `category.php`. This redirects, but link doesn't go to first child post. How can I redirect to the first child post, in ASC order by date?
/*
Category Template:
Template URI:
Description:
*/
if ( have_posts() ) :
while ( have_posts() ) : the_post();
wp_redirect( get_permalink( $post->ID ) );
endwhile;
endif; | You are much too late in the page load sequence to redirect. You need to redirect before headers are sent to the browser. The `template_redirect` hook should be a pretty good option:
function redirect_cat_wpse_207298() {
if (is_category()) {
global $post;
wp_safe_redirect(get_permalink($post->ID));
die;
}
}
add_action('template_redirect','redirect_cat_wpse_207298'); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "categories, redirect"
} |
Stop refresh event in customizer
How can I stop the `refresh` event for the Customizer iframe? Something like:
wp.customize.refresh( function() {
return; // or whatever would stop the refresh
} );
The background: I'm using Kirki to add a code editor field to the front end Customizer. It gets an option from my theme option's custom CSS area (not a theme I developed, so I cannot use traditional theme_mod) and I can properly get/put the data from this option to write custom CSS from the front end Customizer.
For the live edit to work, I modified the front end custom CSS `<style>` element to have a unique ID, and using CodeMirror's `update` event I can replace the `<style>` element's contents successfully and see the live changes. However, the Customizer `refresh` event also fires just moments after, thus wiping out the updated `<style>` element. | I found the answer here: <
Using 'transport' => 'postMessage' in my fields settings array. Kirki also provides passing this option too. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme customizer"
} |
Gravity Forms merge tags in templates?
Is there a way to put Gravity Forms merge tags in template.php files or other sections of the website? A plugin maybe? I need to retrieve a field value from one of my Gravity Forms and use it in the post that is created with the form.
I'm having a hard time figuring out how to actually retrieve the data submitted from the Gravity Form and using it in other places on my site. I'm hoping this is possible as it seems like it would be a very basic feature of the Gravity Forms plugin. | The ability to use Gravity Forms' merge tags in your post content might be helpful to you here:
<
If you need more specific control, you can fetch an entry like so:
$entry = GFAPI::get_entry( $entry_id );
And echo out a specific field's value from that entry like so:
echo $entry[1]; // replace "1" with your desired field ID | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, templates, plugin gravity forms"
} |
Show number of posts by logged in user
How to display the number of posts written by the logged in user.
Here is what i got from the codex so far
<?php echo 'Number of posts published by user: ' . count_user_posts( 5 ); ?> | Here a code example with explanation in the comments:
// First a check whether the use is logged in or not:
if ( is_user_logged_in() ) {
// The user is logged, retrieve the user id
$user_ID = get_current_user_id();
// Now we have got the user's id, we can pass it to the function 'count_user_posts':
echo 'Number of posts published by user: ' . count_user_posts( $user_ID );
} else {
// The user is not logged in
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, users, post meta, user meta"
} |
Store value in cookie
I'm doing a database query in a page, and afterwards I want to store an id - I thought I could do it in $_COOKIE?
But it doesn't seem to work to just create a parameter and set a value to it, like:
$_COOKIE['member_id'] = $wpdb->insert_id;
How can I simply add a key and value to the cookie array? | Use `setcookie()` like shown below:
setcookie(
$name,
$value,
time() + 3600,
COOKIEPATH,
COOKIE_DOMAIN
);
_Note:_ `$wpdb->insert_id` AFAIK will always return `false` or `1`, so I'm not sure if that will be of value for your. I might be wrong about that see @s_ha_dum's comment. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "cookies"
} |
WP Ubuntu/Mac image conversion differences
On my local Mac when i upload a image it gets converted into a 300x300 thumbnail which looks good
When i upload the same image on my ubuntu based production server the quality is worse than my local mac and the image file size is larger.
Does anyone have an idea why that is?
The theme used is EXACTLY the same. Plugins are the same. Wordpress is the latest on both machines: 4.3.1.
i have attached both images to show the difference:
# From mac
from mac
# From ubuntu server
from server | I assume, probably either different settings for the image processing library or different libraries in use, e.g. ImageMagick on local and GD on production. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "mac"
} |
How does ifttt.com authenticate a supplied WordPress account
I'm curious to know how ifttt.com authenticate a supplied WordPress admin login credentials. And after authorization is granted, how does it publish post on our behalf? am curious to know what communication protocol it is using. | IFTTT.com connects to your WordPress site via XML-RPC, as the dudes at wpbeginner.com already found out:
> Go to IFTTT and create your account. IFTTT works with all WordPress.org self-hosted blogs (version 3.x and above) and WordPress.com blogs as well. You MUST have XML-RPC enabled to work with IFTTT. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 4,
"tags": "authentication, authorization"
} |
Drop Down Category Menu Not Working
If you look on my website, at the top menu under Member's Only, the dropdown menu is not showing the three pages that are listed as sub-pages under the menu category. I know that the back end is fine, and this theme is an older one that I was using on another site and know this functionality works. Just thinking that maybe something is off with the JS?
This is the code in the header menu:
<div id="main-nav">
<?php wp_nav_menu( array(
'menu' => 'Main Navigation',
'container' => false,
'items_wrap' => '<ul class="nav">%3$s</ul>',
'depth' => 3,
'walker' => new | Make a custom link with the name "Members only" and link to "#". Then add the sub-menu page. | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 0,
"tags": "jquery, css, dropdown"
} |
Change the_content() in Theme Thirteen
I worked with site created on Theme Thirteen and theme uses
`<?php the_content( __( 'Continue reading <span class="meta-nav">→</span>', 'twentythirteen' ) ); ?>` to get post title, date, part of content and read-more link.
But now I need to show only post date and entire post content, but I can't find how to do that. If I try to use `<?php the_content(); ?>` I get the same if I use `<?php the_content( __( 'Continue reading <span class="meta-nav">→</span>', 'twentythirteen' ) ); ?>` How to get post date and entire post content in template ? | You probably have a read more tag in your posts, so you will need to remove them.
We can use the `the_content` filter to achieve that. We need to search and replace the `<!--more-->` tag with nothing.
You can try the following: ( ** _NOTE:** The following code is untested_)
add_filter( 'the_content', function ( $content )
{
return str_replace( '<!--more-->', '', $content );
}, 11 ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "categories"
} |
Right procedure when you develop a WP Website for a client
i don't know if this procedure could be incorrect while you develop a WP website for a client, but i worked like this for years:
1. create a database and sub-domain on my server
2. install Wordpress and the relative template
3. start to develop the website
4. When everything is ok for the client export the Website (plus the Database) and import it on client's domain.
Is this procedure "correct"? | This is a suitable method. There are plenty plugins in the WP Plugin Directory that can 'migrate' your site for you including plugins and their settings. All you then have to do is create a database on your clients site (and possibly directory if required) and then import your clients site/files/data.
Another thing you can do if the client site your working on is going on a new domain name / directory that they have never used before you can develop the site live on that domain if you must but I would recommend password protecting the directory until its ready to be viewed publicly. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, customization"
} |
Access general settings trough wordpress files
I was reading an article about HTTPS and that you could turn on SSL and HTTPS for Wordpress quite easily.
However in the article it said that you should go to Settings > General Settings within the admin panel and change Wordpress Address (URL) and Site Address (URL) from http:// to
However after doing this I'm no longer able to access my admin panel as it always wants to go to https. I just get to a page that says "This webpage is not available"
So my question is, would it be possible for my to navigate trough the Wordpress Install files and undo this? | You should be able to amend those items from the database.
In the table `wp_options` there are the option_names `home` and `siteurl` \- editing these back to the `http` version should do the trick.
You might also want to check your `wp-config.php` file for the following:
define('WP_SITEURL', '
define('WP_HOME', '
And remove the 's' here as well.
Turning on HTTPS and SSL for WordPress is very easy and what you have done will work - so long as you have already uploaded and installed a valid SSL certificate onto your server, without this there is no way for the server to actually be certified, and the https website url will not work. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "options, https, http"
} |
How can I hide the entire "Shipping Details" block on the admin side of Woocommerce?
My Woocommerce store has virtual products that don't require shipping. I have disabled the shipping options from the customer on checkout, but now I want to hide it on the backend as well.
When viewing orders on the admin side, I have 3 columns: General Details, Billing Details and Shipping Details. I want to remove the Shipping Details in the third column so that later I can add some custom fields there instead.
I've tried using
remove_filter( 'woocommerce_admin_shipping_fields', 'filter_woocommerce_admin_shipping_fields' );
but that doesn't change anything on the backend.
I could probably do it with some deeply complicated CSS and display:none, but I'd rather just remove it programmatically, like with a remove_filter or something. | There is no "clean" solution for what you are asking.
However, you can manually delete this block by editing woocommerce/includes/admin/class-wc-meta-box-order-data.php line 315-397. | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 0,
"tags": "woocommerce offtopic"
} |
Twilio Easy Call plugin
I installed a plugin to my website called Twilio Easy Call.
The plugin description says I have to put the shortcode on a page.
Any idea how I can place this shortcode? Is it just copy/paste? | [wpc2c number='your_phone_number_here'] | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "plugins"
} |
Add loggedout class on body using a function or JS
Is it possible to add a class `loggedout` on the body of every page for all logged out users using a function or JS?
My theme already adds a class 'loggedin' for all logged in users. | Presumably your theme is using the `body_class` function to output classes. You can add a filter to remove or add your own classes.
function wpd_logged_out_body_class( $classes ) {
if( ! is_user_logged_in() ){
$classes[] = 'loggedout';
}
return $classes;
}
add_filter( 'body_class', 'wpd_logged_out_body_class' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, jquery"
} |
Custom post type and taxonomy cross registration
I intend to set up the following:
* CPT: job, team-member
They share
* taxonomy: location
When I register location, I do this:
$args = array(
....
'hierarchical' => false,
'rewrite' => array( 'slug' => 'location' ),
);
register_taxonomy( 'location', array( 'team-member', 'job' ), $args );
My question: Do I need the 'taxonomies' line below
register_post_type('job', array(
....
'rewrite' => array('slug' => 'careers'),
'taxonomies' => array('location'),
));
Explanation is appreciated. Thanks. | You don't need both, one of them is enough. However you need to do it in a order when thing you are adding support to is already registers.
So in first case you need to define CPT _before_ taxonomy and in second case _after_.
The third way would be to use `register_taxonomy_for_object_type()` which let's you do this after _both_ are registered, regardless of order. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, custom taxonomy"
} |
Custom field value not saving when it contains a URL?
I implemented a custom field into one of my post formats called 'url'. When I enter a random string of characters into the field, it saves just fine and I display it in my template like this:
`<h2><a href="<?php echo get_post_meta($post->ID, url, true); ?>"><?php the_title(); ?></a></h2>`
However, whenever I enter a URL into this field, i.e "< the value doesn't save. What is going on here? Am I doing something wrong or do I have to treat URLs differently? | After some testing, I figured out the issue. With the Advanced Custom Fields plugin, you have to make sure your field name is unique in order for it to save properly. For some reason, I had another custom field name called 'URL' that was interfering with my 'url' custom field. After changing the name of my custom field, it all works perfectly. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "php, custom field, templates, meta value"
} |
Password protect wp-login.php
AS the title says, how do i password protect wp-login.php page? So the user has to write a specific code to enter. If possible there should be more than one code. | You can use `.htaccess` to protect your wp-login.php. The Codex describes how to do so.
There are also some plugins which do that job for you, finding and choosing a good one is up to you. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "password"
} |
Why is an empty result an error? ( $wpdb->get_row )
I have a query where I get the highest id from a table.
$user_id = $wpdb->get_row("SELECT * FROM $table WHERE id=(SELECT MAX(id) FROM $table)")
The table should always have rows, but if for some reason it returns empty, there is an error (printed with `$wpdb->print_error()`):
WordPress database error: []
I was wondering why an empty result means an error? And how would I prevent this error? | There isn't an error. The square brackets are empty-- aka "no error". Put a spurious comma in the SQL and you will see what I mean.
But your SQL is wildly complicated for you are doing. That is entirely equivalent to
SELECT * FROM $table ORDER BY id DESC LIMIT 1
Though, I notice you are using `id` rather than `ID` and I don't remember any Core tables using the lowercase version. If this is meant for a Core table that will be a problem. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wpdb, get row"
} |
Shortcode not working in widget
I created the following shortcode:
function newsletter_signup_shortcode( $atts ) {
$post_type = get_post_type();
// Attributes
extract( shortcode_atts(
array(
'location' => get_permalink(),
'show_title' => 'yes',
), $atts )
);
// Return the unfiltered content if we're not on a post.
if ( $post_type != 'post' ) {
return $content;
}
ob_start();
?>
<!-- MailChimp Signup Form outputs here - code omitted for clarity -->
<?php
// Add the opt-in form after the post content.
return $content . ob_get_clean();
}
add_shortcode( 'newsletter_signup', 'newsletter_signup_shortcode' );
This works great on the home page and blog post pages, within the post and in the sidebar widget.
However, when I view a page, the sidebar widget does not display the shortcode content:
What am I missing here? | You have a conditional in your function that will skip (return) if the current "view" is not a single post. You also have an undefined variable `$content` \- the following has the condition removed and undefined variable fixed (always, always have debugging on when building with WordPress):
function newsletter_signup_shortcode( $atts ) {
$post_type = get_post_type(); // Not sure if you still need this for your MailChimp template?
// Attributes
extract( shortcode_atts(
array(
'location' => get_permalink(),
'show_title' => 'yes',
), $atts )
);
ob_start();
?>
<!-- MailChimp Signup Form outputs here - code omitted for clarity -->
<?php
return ob_get_clean();
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "widgets, shortcode"
} |
Send notification to the admin when new custom post is submitted
I have a cpt called "auto" and i make a frontend form to create new post with "pending" status. After the post submission i would receive an email with a notification of the new post.
function newpost_notify() {
$mailadmin = '[email protected]';
$subject = 'Subject';
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
$headers .= 'From: xxx <[email protected]>' . "\r\n";
$message = 'There\'s a new post.';
wp_mail( $mailadmin, $subject, $message, $headers );
}
add_action( 'publish_post', 'newpost_notify', 10, 2 );
This is my code..but i didn't receive any email.
I would know if there's a difference between a "new post" and a "publish post", because i read something about the post status transition.
Thank you | EDIT - SOLUTION
I got the solution using status 'new_to_pending' and adding the $auto object.
function newpost_notify( $auto ) {
$mailadmin = '[email protected]';
$subject = 'Subject';
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
$headers .= 'From: xxx <[email protected]>' . "\r\n";
$message = 'There\'s a new post.';
wp_mail( $mailadmin, $subject, $message, $headers );
}
add_action( 'new_to_pending', 'newpost_notify', 10, 2 );
thanks to the constructive comments of @Rarst & @flomei | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom post types, customization, wp mail, notifications"
} |
Filter the first <blockquote> from Quote Post Format
I want to get the first blockquote from the post (even if the user writes only one, or more than one) in the Quote Post Format, in order to show it in the archive Loop. For example:
$quote = has_post_format( 'quote' );
if ( $quote ) {
if ( *the post has no quotes* ){
// Don't show anything
} else {
// Show the blockquote from the post (if there's only one),
// or the first one (if there are more than 1)
}
}
Is there something like this? | I finally found a solution that works. In case you need it, here it is:
<?php
if (has_post_format('quote', $post->ID)) {
$content = trim(get_the_content());
// Take the first quote from the content
$quote_string = extract_from_string('<blockquote>', '</blockquote>', $content);
// Make sure there's a quote on the content
if (!$quote_string == "") {
// Get the first quote and show it on the Loop
echo $quote_string;
} else {
// If not, show nothing
}
}
?> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "post formats"
} |
WP_Query for products always returns empty
I have a simple following logic:
$args = array(
'post_type' => array('product'),
'product_cat' => 280,
'posts_per_page' => 3
);
$category_posts = new WP_Query( $args );
if($category_posts->have_posts()):
$result = '<div class="three-products">';
while($category_posts->have_posts()):
the_post();
$result .= '<div class="one-product">'.the_post_thumbnail( 'thumbnail' ).'</div>';
endwhile;
$result .= '</div>';
wp_reset_postdata();
return $result;
else:
_e( 'There were no products matching your criteria.' );
endif;
I am sure that there are products in category 280, however have_posts always returns false.
If I comment that line out, it seems to end in infinite loop and does not load page at all.
Any help or guidance is much appreciated. | Your arguments should look like this :
$args = array(
'post_type' => 'product', // No need for an array since you only query one post type
'posts_per_page' => 3,
'tax_query'=>array( // The taxonomy query
array(
'taxonomy' => 'product_cat',
'field' => 'term_id', // Can be omitted, default parameter, can also be 'slug' or 'name' (name should be avoided as @Pieter Goosen says)
'terms' => 280 // You can use an array to include multiples terms i.e. array(280,281)
)
)
);
It doesn't work because wordpress only handle native taxonomy (category), for custom taxonomies, you must use a tax_query. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query, woocommerce offtopic"
} |
Modify Image Source With The_Content Filter?
I'm very inexperienced with regex, however I'm trying to create a function that filters through `the_content()` and `get_the_content()` in order to modify the SRC of all images. The intended purpose would be to modify the URL's to use ` instead of ` This would allow posts to utilize the Photon API without needing the JS side of Photon..
I know I need to hook into `the_content()` using a filter in order to accomplish this, but I was unable to accoplish this using `str_replace()`, so I'm assuming using `preg_replace()` would work.
Also, if it's possible to add `?quality=70&strip=all` to the end of the URL this would help decrease page speed.
Any thoughts? | Let's give it a try:
$str = '<img src=" />';
$pattern ='#<img src=" />#';
$replace = '<img src=" />"';
$result = preg_replace($pattern, $replace, $str);
The $pattern is quite simple and very specific. You might need to generalize it a bit more but it should show you the direction to go. E.g. it takes no care of possible whitespace. A first attempt to take care of this:
$pattern ='#<\s*img\s*src\s*=\s*" | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "posts, images, filters, the content, regex"
} |
Creating new menu item
I'm looking for a way to create a new item that can be added to a menu.
Here are the details of my problem: I use WPML. WPML have that nice feature that you can add the switcher to a menu, automatically. It adds it at the end of the menu, no control on that.
Thing is, I want my language switcher to be element 4 out of 6. That feature to automatically add the element at the end doesn't fit my needs.
So I want to create a new element that can be used in apparence->menu to put my language switcher exactly at the spot I want it.
Is there any way to do that?
TLDR: I want to be able to push custom HTML/PHP code in a menu element (Apparence->Menu). Any functions to do so? | Following code snippet replaces placeholder menu item from 'your-menu' menu.
add_filter( 'wp_nav_menu_items', 'add_item_to_menu', 10, 2 );
function add_item_to_menu( $items, $args ) {
if ( $args->theme_location == 'your-menu' ) {
$link_text = "My Replaced Link Text";
$link_url = "my-replaced-link-url.com";
$items = str_replace( 'lang_placeholder_text', $link_text, $items);
$items = str_replace( 'lang_placeholder_url', $link_url, $items);
}
return $items;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "php, menus"
} |
get_users() not returning all users in site
I'm fairly new to wordpress/php development, so forgive me if this is a stupid question.
I'm trying to get a list of all the users with metadata in order to export them to a CSV file.
We currently have 69 users on the site, but the get_users() method only lists 4 users.
I'm currently using the below piece of code.
$args = array(
'fields' => 'all'
);
$users = get_users( $args );
Thanks in advance | ederoock,
I'm not sure why you're only seeing 4 of the 69 users with the code provided, but I can tell you that the `$fields` parameter of the `get_users()` function can be set to 'all_with_meta'.
Change your array from `'fields' => 'all'` to `'fields' => 'all_with_meta'` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development"
} |
Is there a way to switch to another theme?
Is there a method that exists that will let me switch the theme?
**Update:**
It looks like switch_theme is the method and there is also an event of the same name. It says that it accepts an argument of stylesheet and for backwards compatibility it accepts, $themename and $stylesheet. I guess I don't understand, why is someone changing the stylesheet and no longer changing the theme? | `switch_theme()` is the function you need but this...
> why is someone changing the stylesheet and no longer changing the theme?
... indicates a misunderstanding. You provide the `$stylesheet` as an argument but you are switching the theme as a whole not just the stylesheet. And, for reasons unknown, `$stylesheet` isn't the stylesheet. It is:
> `$stylesheet` is the name of your folder slug. It's the same value that you'd use for a child theme, something like `twentythirteen`.
>
>> < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development, themes"
} |
Choose either excerpt or the_content
I'm having a hard time figuring out how to set either the excerpt or the full content on my posts. I'm using post format, so far everything works, but when I click on a specific post, only the excerpt is displayed in the full post (because only the excerpt is set on format-video, for ex.).
I would like my post formats to display the excerpt when it's on loop.php (home page), and the full content when it's on single.php I am bad at php, but here is my code (which is obviously not working for a reason)
<?php if ( is_loop() ) { ?>
<?php custom_excerpt('custom_index'); ?>
<?php } elseif ( is_single() ) : { ?>
<?php the_content(); ?>
<?php } ?>
<?php endif; ?>
Could anyone tell me where is the mistake in my code ? Or is there a better solution to perform what I'm trying to do ? | You can try this.
<?php
if ( is_single() )
the_content();
else
custom_excerpt('custom_index');
?>
in your post loop.It prints content if the post is single.php page otherwise custom_excerpt() data. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php"
} |
Custom post type as child of page
I am wondering if it's possible to have a page, let's say called 'books' with some listed books.
Next to this normal page we create an custom post named 'books' were we collect our books.
Nou I already have the url domain.com/books/ with the overview of all my books, I am wondering how I need to configure the custom post to use this page as parent to generate an url as domain.com/books/the-title-of-the-book/
Thank you! | If you want your custom post type listed under a page you can add the permalink of the page to the rewrite slug like so:
register_post_type('my_books', array(
'has_archive' => false, // Stops domain.com/book becoming the cpt's archive
'rewrite' => array('slug' => 'book')
));
You need to visit `Settings->Permalinks` after making any changes to permalinks to re-generate them. You should now be able to visit books under `mysite.com/book/my-book-slug` and visit your manually created Page under `mysite.com/book`. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "custom post types, permalinks, routing"
} |
How to limit the pages shown in the page manager to those created by the logged in user?
I am a high school teacher (not a developer by any means), and I run a small WP site for my classroom. All of my students are contributors to the site, and I use a combination of several plug-ins in order to manage their access.
When students log into the backend and visit the "All Pages" page, they can see the titles of everyone's pages, not just their own, by clicking on the filters for "All," "Published," "Drafts," etc. I would like to remove this capability.
The phenomenal plug-in, Manage/View Your Posts Only, has done exactly this when it comes to posts. Students are only able to see their own posts from the "All Posts" page. However, this feature does not apply to pages.
Is there a way to create this functionality for pages? | There is a way to do this code. You can hire a dev or check out this plug in: < It looks to have the features you need.
If you are interested in diving into the backend, the place to get started is by building custom page templates. Here is some good resources on page templates: <
and the code to redirect non admin users away from that page:
<
I hope that helps! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "pages, user roles"
} |
How one category can have different fields?
_I am new in WordPress but before I worked with Drupal and it is different and I am a little confusing now._
I am going to make a website for a **travel agency,** and one of the categories that they have is hotel. That is list of hotels that should sort by name of cities. then when I click on one city's link, **they want to show the list of hotels of that city sort by their rating.**
_I really don't know a lot about WordPress and I get confusing, and I don't know what should I do._
I want to have a category that is about hotels, and let the editor of website to post a hotel and fill out some different fields about hotel. **fields like** stars, city, country, address ...
_In Drupal, that was easier by **views** , but I like to learn WordPress and the website should be in WordPress. In Drupal it is really easy to add custom fields_
Please show me a way and I need your help | The very _very_ rough guess at what data architecture for it might look in WordPress would be:
* hotel is a Custom Post Type (individual items of something)
* city is a term of custom taxonomy (group of items)
* stars and similar data are custom fields (specific data attached to items)
However there are numerous nuances in all of this, which is WP development essentially consists of. :)
WP also isn't particularly helpful about building UIs for custom things. Taxonomies more or less have UI provided, but with custom fields you are mosly on your own. On other hand there are dozens of third party frameworks around that aim to help with building out just that. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, themes"
} |
How to add same body class in multiple pages using their page id?
add_filter( 'body_class', 'custom_body_class' );
function custom_body_class( $classes ) {
if ( is_page( '38034' ) ) {
$classes[] = 'new-class';
return $classes;
}
}
Above code works fine to add a class in a page which id 38034. Now I want to add same class in multiple pages, how I can do that?
can I write `if ( is_page( '38034, 10883, 12031' ) ) {`
Note: I have no php knowledge. | Note that you must **always return** the classes in your callback.
So move this part:
return $classes;
out of the `if` condition.
The `is_page()` does support multiple ID's when it's in an array.
This should work:
add_filter( 'body_class', 'custom_body_class' );
function custom_body_class( $classes ) {
if ( is_page( [ 38034, 10883, 12031 ] ) ) {
$classes[] = 'new-class';
}
return $classes;
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "body class"
} |
Option Tree integration of Custom CSS
I would love to integrate Custom CSS field from my Option Tree plugin to the code, but if I try to integrate them following way into `functions.php`, it ends up with _Fatal error: Call to undefined function ot_get_option() in /data/web/virtuals/51889/virtual/www/domains/demo.kybernaut.cz/ommo-wp/wp-content/themes/ommo/functions.php on line 36_ So it looks like that I call the function before loading `ot_get_option` function from Option tree, is that possible? What to do with it? Thanks a lot!
//Custom CSS
if (ot_get_option('css', false) != false) {
function css() {
return '<style>'.ot_get_option('css').'</style>';
}
add_action( 'wp_head', 'css', 100 );
} | never* execute code outside of hooks as you are more likely to call a function or use a variable before they were declared and initialized.
your code should be
function css() {
if (ot_get_option('css', false) != false) {
echo'<style>'.ot_get_option('css').'</style>';
}
}
add_action( 'wp_head', 'css', 100 );
*never say never, but this is a rule to follow unless you have a very explicit reason to ignore it. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "functions, theme options"
} |
How can I allow a custom taxonomy for certain roles?
Im trying to only show a taxonomy for the `editor` and `administrator` but I haven't found a solution on SO or here. The closest thing I was able to find was How do I remove a taxonomy from Wordpress? on SO. What is the proper way to only allow the taxonomy for the `editor` and `administrator`?
// remove from everyone that isn't admin or editor
function taxonomy_for_admin_and_editor_only() {
if ( !current_user_can( 'administrator' ) || !current_user_can( 'editor' ) ) {
register_taxonomy( 'foobar', array() );
}
}
add_action( 'init' , 'taxonomy_for_admin_and_editor_only' );
I've tried `add_action( 'admin' , 'taxonomy_for_admin_and_editor_only' );` with no luck either. | When registering your taxonomy you can pass an argument called **capabilities**. Simply passing capabiities that only admins and editors have.
$args = array(
'capabilities' => array( 'manage_options', 'edit_posts' )
);
register_taxonomy( 'foobar', 'post', $args );
< | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 1,
"tags": "custom taxonomy, admin, editor"
} |
Is there a way to change a post's thumbnail image(s)?
I just recently finished the first version of a blog (here: < ), but whenever I share a post on social media, the thumbnail image is the atrocious scaled up version of one of the social media icon's I have on the footer.
I would really like that the thumbnail image be the logo which is on top of the site. According to my research, I could make it my Blavatar, however I ended up discovering that I could only use that if the host was also Wordpress, which it isn't.
Regardless, what could I do (if anything) to use better images to appear on my thumbnails whenever sharing links? I have also attempted to add an image on the post, but that doesn't come as an option for the thumbnail image either.
Thank you very much! | Facebook scrapes your pages for images to go along with the post you share. When it finds an image on the page it will use that.
To specify which image exactly you have to use Open Graph tags in the `head` part of you html page. The `og:image` tag in particular:
<meta property="og:image"
content=" />
Here is a list of plugins that insert the Open Graph tags for you. If you like to put the Open Graph-tag code in functions.php yourself, check this article.
Good luck! | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "post thumbnails, thumbnails, social sharing, sharing"
} |
Slider should be display in home template
I am using WPExplorer Elegant Theme. Slider display in Front page as well. But if i make my blog page (Front) then i don't want to display slider in blog page. I want that slider should be display in specific template. Below is my homepage-silder function code
if ( !function_exists( 'wpex_homepage_slider' ) ) {
function wpex_homepage_slider() {
global $post;
if ( ! is_front_page() ) return;
// Get slides
$wpex_query = new WP_Query(
array(
'post_type' => 'slides',
'posts_per_page' => '-1',
'no_found_rows' => true,
)
);
while this code is place in header.php
<?php
// Displays the homepage slider based on the slides custom post type
wpex_homepage_slider(); ?> | Just removed `if ( ! is_front_page() ) return;` from function homepage-slider. And moved
<?php
// Displays the homepage slider based on the slides custom post type
wpex_homepage_slider(); ?>
in my desire template from header.php | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, themes"
} |
How to change text of a widget depend on condition?
I have text widget with default ads on it ( google ads for example ).
Sometime, depend on condition like location, time, I need to change the default ads from code, just temporary only.
Is there anyway to do that? | It should be pretty easy to alter the text for the Core text widget via the `widget_text` filter:
function conditional_text_widget_wpse_207957($text) {
if (is_single()) {
$text = "Whoa, d00d! I'm single";
}
return $text;
}
add_filter('widget_text','conditional_text_widget_wpse_207957');
You do not specify what conditions you need exactly, nor provide any detail about the changes you need. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "widgets, text"
} |
Can I use namespaces in my plugin?
I am building a plugin that I hope to eventually put on Envato CodeCanyon.
Currently I am creating functions of the form `mypluginname_action`. This is quickly becoming silly as I have to do that a lot. I'm thinking of using PHP namespaces, but I'm worried that there might be a reason why I shouldn't.
1. Are namespaces compatible with WordPress and Envato's coding standards?
2. Can I use namespaces in the PHP versions that I should be supporting?
3. Are there any professional theme/plugin makers who make use of the namespace feature? If not, why not? Are there any common pitfalls with using namespaces?
I am well aware that I can research all of this myself, and of course I will, but as I'm early in development, at this point I'm hoping for a quick answer from more experienced people who might have already looked into this.
I appreciate any thoughts on this. | It's almost four years after I asked this question. For anyone reading this now, namespaces are officially supported. From the 5.2 release notes:
> The minimum supported PHP version is now 5.6.20. As of WordPress 5.2, themes and plugins can safely take advantage of namespaces, anonymous functions, and more! | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugin development, coding standards"
} |
Load plugins'.mo and .po files from a directory
What I'm trying to do is simple: I have so much WordPress plugins, and 3/4 of them aren't translated in my language, so I want and can translate them all without problems, but I would insert translations inside a directory, so everytime I update plugins I don't have to re-upload in every plugins folder the translation...
Could this in some way be achieved?
It's like as a **child theme** works; so if you insert for example, _header.php_ in child theme, WordPress will load code from there.
Practically I would create a directory like **wp-content/translations/name-of-plugin/en.mo** ; exists any way to tell WordPress to use that directory to take translations? Thank you! | This is, in fact, already available by default. If specific locale isn't available in plugin's folder WordPress will try to fallback to languages directory.
It is defined by `WP_LANG_DIR` constant and for plugins the default location would be `wp-content/languages/plugins`. Note that name is expected to follow the specific format: `name-locale.mo`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugins, translation"
} |
Theme RTL semi work but with "?rtl=1" fully work
I have a theme which support RTL. RTL direction semi work with WPML plugin, but when I add `?rtl=1` to URL it work fully. I mean it switch direction in the correct way.
How I can switch direction without add `?rtl=1` to each URL? | Looking at the source, there is no programmatic way to accomplish that. There is only one location where `$_GET['rtl']` is referenced and its value is used directly (i.e., it is not used to set the value of another variable used in the plugin). The function you would want to modify if you want the same effect without passing the `rtl` parameter is `function _show_post_content()` in `inc/translation-management/translation-management.class.php`. Specifically this block of code looks to be the only place affected by the parameter:
[...]
if ( @intval( $_GET[ 'rtl' ] ) ) {
$rtl = ' dir="rtl"';
} else {
$rtl = '';
}
echo '<html' . $rtl . '>';
[...]
You could just remove the if/else statement all together and change the echo to `echo '<html dir="rtl">'` for a quick "hacky" fix if desired. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "language, plugin wpml"
} |
Is there a hook before the user is authenticated?
I'm looking for a hook that can be used before WP reads the DB to authenticate the user's login credentials, but can't seem to find one anywhere. Does one exist?
I tried `add_filter/action('authenticate', 'customcode', 30, 3)`, but this seems to execute as soon as the `wp-login.php` page is requested, rather than after the user hits login and the username/password is `POST`. | Ah, turns out `add_filter/action('authenticate', 'customcode', 30, 3)` was what I was looking for...
The problem was, I had the priority too low so whatever response I was creating with my custom code was over-ridden by the other filters.
So dumping `global $wp_filter['authenticate']` I could see the following filters:
20, wp_authenticate_username_password
30, wp_authenticate_cookie
99, wp_authenticate_spam_check
By changing the priority to 100 (or higher), I could do the overriding instead and create the response I wanted for handling the login credentials submitted via the login page. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 7,
"tags": "hooks, login"
} |
You need to login with a user that has edit posts capacity?
I have a network blog and after the user has created a site they are getting an error when trying to save their post:
> You need to login with a user that has edit posts capacity
Shouldn't they have edit posts capacity when they've created their account? | _Short answer:_
Incorrect URL. Was trying to save to the network path and not the user path.
_Long answer:_
I have a network blog. I have an examples blog with the default user. With the default user I made posts. When a new user signs up they get a copy of that post locally on the client side (JSON of the post data). It is a duplicate they can use to get started. When default user saves it works fine because he is at the default network path. When a new user saves it does not work because new user cannot save to default path. New user can only save to new user path.
Default user path:
> <
New user path:
> <
The client side JSON object that was duplicated was trying to save to the original URL (this worked for default user who has same path):
> <
Once I updated the path to new users site:
> <
...he was able to save the document.
The error message was correct. My code was incorrect. However, the error message could have contained more information. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "multisite, permissions"
} |
Run "the loop" in a random order
I'm using a transient to store a query that gets 60 posts and makes a mosaic of background images, because it improves performance greatly.
The query has 'orderby' =>'rand' set, but obviously when it's retrieved from the transient it displays the same each time.
My question is, can I make the loop display the results of the query in a random order? This would then equal my original state with much better performance.
Thank you. | As I understood, you want the same results but randomize their order. So, you need to shuffle that results. That is quite simple using `shuflle()` PHP function. But that function needs arrays, not objects.
You could convert the object from WP_Query to an array or, I think better, use `get_posts()` instead of WP_Query.
$args = array(
// Arguments to get posts
);
$posts = get_transient ( "your-transiente-name" );
if( $posts === false ) {
$posts = get_posts( $args );
set_transient( "your-transiente-name", $posts, "the-expiration-time" );
}
// Shuffle the $post array
$posts = shuffle( $posts );
foreach( $posts as $post ) {
setup_postdata( $post );
// Standard loop stuff
}
wp_reset_postdata(); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "loop"
} |
Custom user role doesn't show up in admin
I followed a tutorial on how to add a custom user role, and when I put this in functions.php:
$result = add_role( 'user1', __(
'user1' ),
array( ) );
..the new user role is supposed to show up in admin, on the "add new user" section, in the "role" dropdown. But it doesn't. Is there something else required for it to work? | There is nothing else required, it (should) work just fine with the code you posted. I've given this a quick test to confirm it is working and it does. So I'm assuming there is another problem somewhere. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "user roles"
} |
When you register a sidebar in Wordpress, is it possible to choose in what order it appears in the admin
I've registered some new sidebars. They are appearing on appearance->widgets screen. However, they appear in two columns and the order is arbituary. Is there a way to config the order and columns in the widget admin screen? | Sidebars are output in registration order, which is implicitly captured by how they are added to a `$wp_registered_sidebars` global.
This can easily be manipulated, for example following code will move `first` sidebar to the start:
add_action( 'register_sidebar', function ( $sidebar ) {
global $wp_registered_sidebars;
if ( 'first' === $sidebar['id'] ) {
$sidebar = $wp_registered_sidebars['first'];
unset( $wp_registered_sidebars['first'] );
$wp_registered_sidebars = [ 'first' => $sidebar ] + $wp_registered_sidebars;
}
} );
register_sidebar( [ 'name' => 'one', 'id' => 'one' ] );
register_sidebar( [ 'name' => 'two', 'id' => 'two' ] );
register_sidebar( [ 'name' => 'first', 'id' => 'first' ] ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "widgets"
} |
How can I query on the year part of a complete date in a custom field?
My posts have a custom field named _production_ _date and formatted YYYYMMDD.
How can I form a meta_query to select only the YYYY part?
$meta_query_args = array(
array(
'key' => 'production_date',
'value' => '2004',
'compare' => '???'
)
); | The handy thing about how ACF stores dates as `YYYYMMDD` is you can treat them like integers and get a similar level of functionality as if you were using "true" dates.
For example, to get all dates after 1st Jan 2011, use `> 20110101`. Those before June 1st 2012? `< 20120601`. And for your case, all dates within 2004? `>= 20040101 && <= 20041231`.
Translated into a meta query:
$year = '2004';
$meta_query_args = array(
array(
'key' => 'production_date',
'value' => array( $year . '0101', $year . '1231' ),
'compare' => 'BETWEEN',
'type' => 'NUMERIC',
)
);
Check out the codex for a full explanation of all the arguments. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 2,
"tags": "custom field, meta query, date"
} |
Change reset password URL returned by wp_lostpassword_url() via plugin
With a plugin how would you change the URL returned by wp_lostpassword_url()?
The function wp_lostpassword_url() returns the URL where users can reset their password.
Function Reference/wp lostpassword url | Just check the source:
515 /**
516 * Filter the Lost Password URL.
517 *
518 * @since 2.8.0
519 *
520 * @param string $lostpassword_url The lost password page URL.
521 * @param string $redirect The path to redirect to on login.
522 */
523 return apply_filters( 'lostpassword_url', $lostpassword_url, $redirect );
There is a `lostpassword_url` filter that should do exactly what you are asking.
function passurl_wpse_208054($lostpassword_url, $redirect ) {
return '
}
add_filter('lostpassword_url', 'passurl_wpse_208054', 10, 2); | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 1,
"tags": "plugin development"
} |
How to use Readmore.js?
I am trying to use Readmore.js for WooCommerce category description "Read more / Close" functionality. I enqueue the JavaScript and add `$('article').readmore();` in the "Insert Header and Footer" plugin, but when the page loads, it gives me this error in the console:
Uncaught TypeError: $ is not a function
(anonymous function) @ (index):205
j @ jquery.js:2
k.fireWith @ jquery.js:2
m.extend.ready @ jquery.js:2
J @ jquery.js:2
Where have I made a mistake and what is the right way to use this JS file in WordPress?
I know how to use it in a simple HTML page, but in WordPress it looks like it's a different story. | The problem is related to wordpress loading jquery in noconflict mode in which the $ shortcut does not work. Try to replace it with an explicit jQuery or wrapt the relevant code in a way which will decalre $ like in the following example
jQuery(document).ready(function ($) {
$('article').readmore();
}); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "javascript, read more"
} |
Why am I getting ERR_NAME_NOT_RESOLVED when I add a site to my multisite installation?
About a year ago, I created a WordPress multisite installation consisting of 5 different websites. Each site is on a different domain in Production, and I'm using an external domain mapper plugin to make this work (I'm not using this plugin locally, only in Production).
I was able to add another site today, but when I tried to access it, I got a blank Chrome page with the "ERR_NAME_NOT_RESOLVED" error. I do not recall having this problem the first time around.
Is there an additional setting I need to account for, perhaps in my config.php or another file? | Upon further investigation, I found that the answer to my problem involved one simple, yet easy to overlook fix: I needed to add this new site to my hosts file. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "php, multisite, wp config"
} |
How to execute custom loop before loop content?
How to execute custom loop before loop content?
<?php
remove_action( 'genesis_entry_header', 'genesis_do_post_title' );
remove_action( 'genesis_entry_footer', 'genesis_entry_footer_markup_open', 5 );
remove_action( 'genesis_entry_footer', 'genesis_entry_footer_markup_close', 15 );
add_action('genesis_entry_content', 'gt_custom_loop');
function gt_custom_loop() {
// this gets executed after the page content, how to make it execute before?
}
genesis();
?> | Try using the genesis_before_content hook.
add_action('genesis_before_content', 'gt_custom_loop');
function gt_custom_loop() {
// this gets executed after the page content, how to make it execute before?
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "loop"
} |
Function to change post status IF current user and post author are the same
I'm looking to force a post to revert to draft if it is published by the author. Here's the function I've wrote so far:
function check_user_publish () {
$user_id = get_current_user_id();
$author_id = the_author_meta( 'ID' );
$postID = the_ID();
if ($user_id == $author_id) {
$query = array(
'ID' => $postID,
'post_status' => 'draft',
);
wp_update_post( $query, true );
}} add_action('wp_update_post', 'check_user_publish');
Logically I think it seems correct but when I make a test post the status does not revert back to 'draft'. I'm testing locally using Vagrant and VirtualBox. | I was unable to find any action called `wp_update_post`. Are you sure it's a valid one? Lets try the hook `publish_post`.
add_action('publish_post', 'check_user_publish', 10, 2);
function check_user_publish ($post_id, $post) {
$user_id = get_current_user_id();
if ($user_id != $post->post_author)
return;
$query = array(
'ID' => $post_id,
'post_status' => 'draft',
);
wp_update_post( $query, true );
}}
_code not tested_ | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "post status, wp update post"
} |
Custom Post Type doesn't use single.php or single-{custom_post_type}.php
I tried to set up a custom post type in Wordpress, and everything worked just fine.
Until displaying a single post from my custom post type. First it didn't automatically use the `single.php` (as it should), and then I tried to create a custom `single-{custom_post_type}.php` but it doesn't even use that one :/
I'm kind of confused now.
**//Edit:**
Solved the problem. Just had to add `flush_rewrite_rules();` after register post type in functions.php
register_post_type( 'communitydeals' , $args );
flush_rewrite_rules(); | Solved the problem. Just had to add `flush_rewrite_rules();` after register post type in `functions.php`:
register_post_type( 'communitydeals' , $args );
flush_rewrite_rules(); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, customization"
} |
Month display in English but required in Swedish?
I am using WordPress settings like below Image:
; ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php the_post_thumbnail(); ?>
<?php endwhile; endif; ?>
<?php get_footer(); ?>
All I am trying to do is pull in the featured image of the posts and display it on the page. But this does not seem to work. The page is blank. I don't know what I am doing wrong but it is probably something simple. Any help will be greatly appreciated.
Thanks | You won't get anything back from your template simply because the loop returns what is in the main query object for that specific page. To see what is actually in the main query object, you should do `var_dump( $wp_query );` outside the loop.
To display custom content on a page template, you will need to run a custom query to pull in the required posts. `pre_get_posts` does not work on page templates, so you will need `WP_Query` or `get_posts` to run a custom query
## EXAMPLE:
$args = [
'posts_per_page' => 6,
// Add any extra query parameters here according to
];
$q = new WP_Query( $args );
if ( $q->have_posts() ) {
while ( $q->have_posts() ) {
$q->the_post();
if ( has_post_thumbnail() ) {
the_post_thumbnail();
}
}
wp_reset_postdata();
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "loop, images, templates"
} |
Bp-reshare alternative
I used the plugin bp-reshare that you can download the latest version here but this plugin doesn't work when you add media with rtmedia which is a most have plugin when using buddypress so is there some other alternatives to share content between users or is there someone pro enough to modify the core bp-reshare plugin
Thank you | Go to Dashboard > Settings > Buddypress > Settings Check rtMedia update and save settings.
;
if ($WP_DEBUG) {
// do something
}
My question is different. | PHP constants don't have the leading `$`. Strictly, this isn't WordPress, but since there isn't a Core `is_debug()` function that I am aware of, what you want is:
if (defined('WP_DEBUG') && true === WP_DEBUG) {
echo 'd00d';
} | stackexchange-wordpress | {
"answer_score": 26,
"question_score": 12,
"tags": "debug, wp debug"
} |
How can I relate custom post types?
I've got a custom post type of product and one of case study.
Each product has a series of related case studies. How in Wordpress can I relate these items?
I'm using CMB2 and a custom multiselect field that allows the user to select the related product for a case study. However, I'm not sure if this is the best way.
Also the page that lists all the case studies for a particular product is very much like an archive page so it would be nice to be able to access it via
/productname/casestudies | There are probably several ways to handle this. I would store the parent product ID for each case study as post meta data for the case study. You can then use a meta query to get all case studies for a product. To display the case studies archive page, add a rewrite endpoint to generate the `/productname/casestudies` rewrite rules. See this answer for how to load a different template for those requests. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, archives"
} |
How to manipulate wordpress template tags' output
take `the_category()` as an example:
Here is the output of the_category function in the wordpress loop:
<ul class="post-categories">
<li>
<a href=" rel="category tag">
Another Category
</a>
</li>
<li>
<a href=" rel="category tag">
Uncategorized
</a>
</li>
</ul>
so we need a way to add attributes like some other classes, data attributes and ... to the list so it outputs something like this:
<ul id="drop1" class="f-dropdown" data-dropdown-content aria-hidden="true" tabindex="-1">
<li>
<a href=" rel="category tag">
Another Category
</a>
</li>
<li>
<a href=" rel="category tag">
Uncategorized
</a>
</li>
</ul> | Here is how I managed to manipulate the output of the_category() template tag.
functions.php:
function add_post_category_list_attrs($the_list) {
$list_id = "post-categories-id";
$category_title = __("Categories");
$list_trigger = sprintf('<a href="#" data-dropdown="%s" aria-controls="%s" aria-expanded="false" class="cat-list-trigger">%s</a>',
$list_id, $list_id, $category_title);
$the_list = substr_replace($the_list, $list_trigger, 0 ,0);
$the_list = str_replace('<ul class="post-categories">',
sprintf('<ul class="f-dropdown" id="%s" data-dropdown-content aria-hidden="true" tabindex="-1">',
$list_id),
$the_list);
return $the_list;
}
if( ! is_admin() ){
add_filter('the_category', 'add_post_category_list_attrs');
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, filters"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.