INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Manually return false for function_exists
I'm having a run at developing a theme options plugin and right now working on implementing a 'hero' header, checking first to see if my plugin is active using:
if( function_exists( 'my_header_function ) ): my_header_function();
else:
/* carry on and output the default header... */
endif;
Now as my hero header depends on whether the image and logo have been uploaded I wonder if I can manually return a 'false' result from my hook in order to have the original conditional in my header carry on an output the normal header.
Any ideas? Many thanks. | Have your function return your HTML rather than echo it. Perform the logic in the function to see if the image/logo are present and only return the HTML if that's the case, otherwise returning null/false.
function my_header_function( $output = false ) {
if ( /*image and logo have been uploaded */ ) {
$output = /* HTML of your hero header */;
}
return $output;
}
Add a check to your hook function to see if your function returns content; if it does, echo it.
if ( function_exists( 'my_header_function' ) && ( $hero = my_header_function() ) ) {
echo $hero;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, hooks, function exists"
} |
Can you run wordpress with multiple domains at the same time (not multisite)?
Every now and then some clients have multiple domains for the same site. For example domain.com and domain.org. Is it possible to have wordpress work with both domains at the same time? I typically see issues when trying to load resources because of Cross-domain access. I know that I could just point domain.com to domain.org in the domain settings, but I was wondering if that's the only way.
I searched for solutions here, but all questions are about how to setup multiple domains for multisites (which makes sense). Just to be clear, I am not running a multisite. | Are you wanting for the exact same WordPress site to work on two different domain names, where all links and content would use either domain name?
If this were the case, you would run into Duplicate Content issues with Google, hurting your SEO pretty badly.
That being said, you still would have a very hard time getting WordPress to properly load your content off of either domain name. A variety of functionality uses the get_site_url function to construct the links on your pages, so all of your links would be using only the one domain within your Siteurl setting.
Even still, if you want to try and get really tricksy, you can use something like the following to define your Siteurl and Home in the wp-config.php based upon the Domain being passed to the site:
define('WP_SITEURL', ' . $_SERVER['HTTP_HOST'] . '/path/to/wordpress');
define('WP_HOME', ' . $_SERVER['HTTP_HOST'] . '/path/to/wordpress'); | stackexchange-wordpress | {
"answer_score": 19,
"question_score": 13,
"tags": "domain"
} |
Merge comments from Facebook with WP comments
I'm looking for a way to integrate Facebook comments (actual comments **from** facebook) into the comment section of a wordpress post?
So what I need is; when someone comments on an URL-post on facebook about for example page.com/post, it shows up on page.com/post as well, merged with comments posted on the page itself.
Is this possible? Is there any plugin I can use for this? | It looks like there are a number of plugins that can accomplish this:
* <
* <
Naturally, I can't really vouch for these plugins working _well_ , but that is the case with any plugin. Make sure to take backups first and good luck! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "comments, plugin recommendation, facebook, comment form, social sharing"
} |
Questions about using Disqus or Jetpack for comments
I'm looking for a good commenting plugin, I want to choose between Disqus and Jetpack, but I have a few questions I **couldn't** figure out myself.
Hopefully you guys can help me out! :)
1) Where are the comments stored, is this in my database on or the Disqus/jetpack server?
2) What will happen if I switch over to default comments after all, will the Disqus or jetpack comments be removed?
3)Facebook is really important, while loggin in on Jetpack/Disqus, will these comment show up on facebook (in the activity feed of their friends) as well? Like normal facebook comments in wordpress?
4) Same with twitter, is there an option to share the comment on Twitter?
Hope you guys can help. Thanks. | I am using Disqus and can anwser for this platform :
1) You have the option to save comments both on Disqus and locally on WordPress.
2) This way, if you want to switch to default comments, they will already be there. On the other side, you cal also import local comments to Disqus, if you were using the default comment system and want to switch to Disqus.
3,4) You can share your comment once created, you can test this yourself on any disqus enabled website | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "plugins, comments, comment form, plugin jetpack, disqus"
} |
Hide a category of posts from main blog, and only show in category view
I would like to hide a post on the main blog page (run on index.php) and have it only show up when the visitor views a particular category.
I have tried the following just before the loop:
<?php query_posts('cat=-208'); ?>
This hides the post in blog view as intended, but when I click into category 208 all posts show up there, even those not tagged with that category. However, the post tagged with that category does not show up there either.
Please help. | I was able to get the result that I wanted by putting the following into the `functions.php` file in my theme directory:
function exclude_category( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'cat', '-208' );
}
}
add_action( 'pre_get_posts', 'exclude_category' );
The result of using this code was that any posts tagged with category 208 do not appear in the main blog, but they do appear in category 208 as well as in any other categories they are tagged with.
To exclude multiple categories, edit the following line of the above as follows:
$query->set( 'cat', '-208,-9,-50' );
You can find full details here.
Thanks to Milo for his comment pointing me in the right direction. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, blog"
} |
Create 3 Level Relations with ACF and Wordpress
i have a more or less huge project and i decided to use wordpress.
I want to create a nutrition plan. Therefore i use custom post types for recipes and advanced custom fields vor values like kcal and so on.
The user can create nutrition plans and there he can add some recipes, so i need to build a relationship from user > nutrition plans > recipes and at the moment i dont have any ideas how to solve this problem with wordpress and acf.
At the moment i have a array with the id's of the recipes and want to save them intro a nutrition plan.
Do you guys have any ideas to build this up? Thanks for help :) | Your "Nutrition plan" post type should use the Repeater Field from ACF: <
Inside this Repeater Field you have to use "Post Object" filtering only your "Recipes" post type: < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom post types, custom taxonomy, advanced custom fields"
} |
How to Display a Single Post Excerpt
Is it possible to show the excerpt for a known and single post (on the Home Page) while in `the loop`?
I tried each of these and none of them work:
<?php echo the_excerpt('10'); ?>
<?php echo the_excerpt(10); ?>
<?php $theExcerpt = get_the_excerpt('10'); echo $theExcerpt; ?>
<?php $theExcerpt = get_the_excerpt(10); echo $theExcerpt; ?> | `the_excerpt()` is one of a few template tags that do not accept a post ID as a parameter. Instead, you need to set up the global `$post`, run your tags, then restore it:
if ( $_post = get_post( 10 ) ) {
setup_postdata( $post = $_post );
the_excerpt();
// Any other template tags for this post
wp_reset_postdata();
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "php, loop, excerpt"
} |
What could interfere with changing iframe contents with href?
On one v4.1 Wordpress site the following code works as expected:
<a href=" target="test">Test link</a>
<iframe src=" height="1000" name="test" id="test"></iframe>
On another, which in contrast to the first site is running Genesis (though I can't tell if that's relevant), clicking the `Test link` opens the source in a new window, not in the iframe. How can I determine what's breaking the reference to the iframe, or the hyperlink functionality, on the second site? | Ah ha: by searching the rendered page for `target` I discovered that the site was running a plugin called "Open external links in a new window." Disabling that plugin solved the problem. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "links, formatting, genesis theme framework"
} |
Creating A New Admin Menu Tab For Theme Options
I 've found an online tutorial that teaches how to implement a simple Options Page for the theme. I did it successfully but it is displaying as a sub menu, and I want it to be a main menu like those admin panel already have such as "Appearance,Plugins,Tools,Settings..." . How can I accomplish it? Here's my code:
add_action('admin_menu', 'add_global_custom_options');
function add_global_custom_options()
{
add_options_page('Global Custom Options', 'Global Custom Options', 'manage_options', 'functions','global_custom_options');
} | Try to replace the `add_options_page` line with the following:
add_menu_page( 'Global Custom Options', 'Global Custom Options', 'manage_options', 'functions','global_custom_options' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "functions, wp admin, admin menu"
} |
No data received
When I use the wp_register_script() and wp_enqueue_script() to load the jquery for the wordpress I got "no data received result with other information like this :
Unable to load the webpage because the server sent no data. Error code: ERR_EMPTY_RESPONSE
My code to load the jquery is
function theme_script(){
wp_deregister_script( 'jquery' );
wp_register_script('jquery',get_template_directory_uri().'/sliderengine/jquery.js');
wp_enqueue_scripts('jquery');
wp_register_script('amazingslider',get_template_directory_uri().'/sliderengine/amazingslider.js',array('jquery'));
wp_enqueue_scripts('amazingslider');
wp_register_script('initslider-1',get_template_directory_uri().'/sliderengine/initslider-1.js',array('jquery'));
wp_enqueue_scripts('initslider-1');
}
add_action('wp_enqueue_scripts','theme_script'); | Your code is wrong. You are confusing `wp_enqeue_script` function and `wp_enqueue_scripts` action. It should be:
function theme_script(){
wp_deregister_script( 'jquery' );
wp_register_script('jquery',get_template_directory_uri().'/sliderengine/jquery.js');
wp_enqueue_script('jquery');
wp_register_script('amazingslider',get_template_directory_uri().'/sliderengine/amazingslider.js',array('jquery'));
wp_enqueue_script('amazingslider');
wp_register_script('initslider-1',get_template_directory_uri().'/sliderengine/initslider-1.js',array('jquery'));
wp_enqueue_script('initslider-1');
}
add_action('wp_enqueue_scripts','theme_script'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "jquery, javascript"
} |
Return only Count from a wp_query request?
Is it possible with the standard build-in tools in Wordpress to get `wp_query` to only return the count of an query?
Right now, I’ve a query which has several meta_queries but what the only thing I’m interested in is the actually count of the query.
I know that I can use the found_posts property but the query itself generates a big overhead by query `SELECT *` and thus returns the whole object.
I could just as easy query the DB with a custom query using `$wpdb` but I would like to utilize the build-in query system if possible..
I’ve been looking for the answer for this on SE and Google but came on empty.
If I've explained myself poorly, please let me know and I'll try to elaborate.
Cheers | There is no build in function to achieve what you want, at least not for complicated meta queries like this. If you need to use build in functions for this, the best will be to make use of `WP_Query`.
To make the query faster and to skip the unwanted returned array of `WP_Post` properties, and because you are only interested in post count, you can use the following in your parameters in your arguments
'fields' => 'ids',
'no_found_rows' => true,
This might even be a bit faster than a custom SQL query, and the results from `WP_Query` is cached as well. | stackexchange-wordpress | {
"answer_score": 16,
"question_score": 13,
"tags": "wp query, query, mysql, wpdb, count"
} |
Gallery Shortcode - only show first x thumbnails
Is there a way to only show the first 6 thumbnails on the actual post but when a user clicks on any of the thumbnails, then he can browse all images in the post gallery?
Essentially, I would like the exact functionality of this code but with only showing the first 6 thumbnails instead of all of them:
[gallery link="file"] | I know this is a bit of cheating but if I use this code essentially I achieve what I want, albeit the thumbnails are loaded on the page unnecessarily..
<div style="height:100px;overflow:hidden;">
[gallery columns="4" link="file"]
</div> | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 1,
"tags": "gallery"
} |
jQuery function not working
I have a very simple jQuery function that is supposed to toggle a div's visibility:
jQuery( ".signUp" ).click(function() {
$('.signUpForm').toggle();
});
The HTML is a simple signup form (hidden fields left out for brevity):
<p><a class="signUp" href="#">Sign Up!</a></p>
<div class="signUpForm">
<h3 class="title">Join our email list!</h3>
<form action="<url goes here>" method="POST">
<label for="email">Email:</label><input type="text" id="email" name="Email"/></br><br />
<input type="Submit" value="Submit" /><br />
</form>
</div>
The script looks like it was enqueued properly, but it's not working on the WP page. It does work just fine on JSFiddle (<
Any ideas what I'm doing wrong?
Thanks. | You need to wrap your jQuery click event in a DOM ready function.
(function($) {
$('.signUp').click(function() {
$('.signUpForm').toggle();
});
})(jQuery); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "jquery"
} |
Shared Custom post type between WP network sites
I'm developing four websites which are separate, besides the Events (custom post type). Three of the websites are WP, and I've got them in a Network. I would like Events to show up in all three Admin interfaces with the same data. All being able to create and edit. Is it possible? It's all the same DB.. | It doesn't seem to be a WP Network main object for getting data from other sites in the Network i.e. _$wp_network->site1->get_post_type('events')_. I solved this using the automatically generated RSS feed for the custom post type. The feed is available on _/[custom post slug]/feed_
**How to read the data from other WP sites**
WP comes with SimplePie for easy RSS operation.
$rss = fetch_feed(' post slug]/feed');
$rss_items = $rss->get_items(0, 10);
foreach ($rss_items as $item) : ?>
<h4><?php echo esc_html($item->get_title()) ?></h4>
<?php endforeach; ?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, multisite, database, admin, wpdb"
} |
Login page is redirecting to homepage
Unable to login because `wp-login.php` redirects to **homepage**.
I tried deactivating all plugins but nothing worked.
I didn't install any plugins or make any changes recently. | Update your DOMAIN site.
Put this in your `wp-config.php` file
define('WP_HOME','
define('WP_SITEURL','
Probably thats fix your problem. Wherever, you can revert back to the Default Theme, renaming the folder of your current theme in `/wp-content/themes/` directory.
Trying too deleting your `.htaccess` file
Regards. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "url rewriting"
} |
Disable requests to api.wordpress.org
I need to suppress outbound requests to api.wordpress.org somehow. They are taking like 1 seconds each and take so many time to load a page when I'm logged as admin.
I've searched for some solutions over the web but they don't seem to work. | You can Disable HTTP Calls by adding this in your `wp-config.php`
define( 'WP_HTTP_BLOCK_EXTERNAL', TRUE );
This will disable/block all external HTTP requests and will make website alot faster.
And then you can whitelist domains that you don't want to block.
define( 'WP_ACCESSIBLE_HOSTS', 'example.com, domain.com' ); | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 5,
"tags": "updates, api, automatic updates"
} |
How to add MailChimp subscribe widget to a page? (not a sidebar widget)
I am trying to create a dedicated landing page where the only thing there will be the sign-up form to join my mailing list.
Is there a way to do that?
I already have MailChimp widget on the sidebar of my blog posts, but this is slightly different.
Thanks! | Mailchimp forms can also be embedded in your page
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin mailchimp"
} |
How to sync user database with "user role editor" plugin enabled
I already know how to sync user database for multiple wp installations from this answer. I don't know how to sync user database with custom user roles.
Thanks in Advance! :) | User roles and associated capabilities are all stored in the `$prefix_options` table in the `$prefix_user_roles` (note that in both of these `$prefix` is a variable, so if your `$prefix` is `foo_`, your table will be `foo_options`). You need to sync this value between databases. As far as I'm aware, there is not a way to sync just this one option beyond connecting to the needed table for it. You will likely need custom SQL for this.
User capabilities should already be synced, as these are stored in the `$prefix_user_meta` table, and syncing that table was covered in the answer that you linked to in your question. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "user roles"
} |
add_meta_box creating default form field types
I'm using `add_meta_box` as per the Codex entry.
My question is about the 'callback' to print the form fields on the admin page.
In the Codex, the form fields are echoed as written out HTML elements, but in some plugins I've looked through, the developers prefer to use 'callback_args' to pass an easy to understand array to pseudo-form elements that is then processed to output the HTML elements with minimal HTML coding. See, for example, this code on GitHub. WooCommerce also has a similar way to build meta boxes for products.
So my question is: does WordPress by default have a similar mechanism or is that a feature that requires a plugin? | Short answer: no. WordPress core has the basic meta box functionality (registering a box & passing a callback) - what that callback does, or how it works, is entirely up to you. You can either code your own implementation, or use a 3rd party as you mentioned. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, metabox, forms"
} |
Term specific featured post on taxonomy archive pages
I am trying to find a way to display a per term featured post on taxonomy archive pages.
So say you navigate to `url.com/my_taxonomy/my_term` it should show the featured post of `my_term` above the results of this page.
Making a post "`featured`" would be done by a custom field named "`featured`", which is a true/false field.
**Edit: the way to go...**
<?php
$obj = get_queried_object();
$post_object = get_field('featured', $obj );
if( $post_object ):
// override $post
$post = $post_object;
setup_postdata( $post );
?>
<div class="featured">
</div>
<?php wp_reset_postdata(); ?>
<?php endif; ?> | The way to go would be to create an archive template for your **taxonomy**. Then you can catch the term requested with a function like `get_queried_object()`. So now you can do a custom `WP_Query` querying for both your term and your meta 'featured'
Hope that makes sense
< < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom field, taxonomy, terms"
} |
Trying to get property of non-object in: $wp_query
I've this function at `functions.php` file:
function custom_secondary_nav( $menu_name, $id = '', $menu_title = '' )
{
global $wp_query;
// others stuff goes here
if (is_object($wp_query)) {
$wpQueryObj = get_object_vars($wp_query);
if (in_array("queried_object", $wpQueryObj)) {
$query_name = $wp_query->queried_object->name !== "" ? $wp_query->queried_object->name : "";
}
}
}
But all the time I'm getting this PHP Warning:
> PHP Notice: Trying to get property of non-object in /var/www/vhosts/elclarinweb.com/httpdocs/sistema/wp-content/themes/elclarin_v2/functions.php on line 86
How I can fix that small issue? | `get_object_vars()` returns an _associative array_ of object properties - so `queried_object` is never _in_ `$wpQueryObj`, it's a key: `$wpQueryObj['queried_object']`.
Besides, you shouldn't be doing any of that anyway - use `get_queried_object()`:
if ( $wp_query instanceof WP_Query ) {
if ( $object = $wp_query->get_queried_object() ) {
$query_name = isset( $object->name ) ? $object->name : '';
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query, functions"
} |
Redirect Image Url to a page via htaccess
I am trying to redirect Image Urls to a page. I have used 301 Redirection plugin, but that doesn't seem to work.
For ex : should redirect to mywebsite.com/page
I have used 'Link to' to 'Media File' in individual image settings since I am using Social gallery plugin and it needs images to be linked to 'Media File' (since it is a Lightbox social sharing plugin)
How can I redirect all the image URls to a page of my choice using htaccess? | You'll need to add a rewrite rule to your `.htaccess`:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_REFERER} !/wp-admin/ [NC]
RewriteRule ^wp-content/uploads/.+?\.(jpe?g|png|gif|svg)$ /my-page [R=301,L]
</IfModule>
Add this after anything added by WordPress. You'll need to replace `/my-page` with the slug of the page you'd like to redirect to. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "images, redirect, urls, htaccess"
} |
Prompted for FTP details even with FS_DIRECT set to true
I am running WordPress 4.1 Multisite on CentOS with NGINX. I have set `define('FS_METHOD','direct');` in `wp-config.php` but am still getting prompted for FTP credentials when trying to install a plugin.
I have tried chmod'ing the `wp-content` directories _recursively_ with both `nginx` and `www-data` users and neither works | Because I had cut and pasted `define(’FS_METHOD’,’direct’);` from the web, the incorrect quote characters were pasted into the file.
should be `define('FS_METHOD', 'direct');`
The incorrect quote character also changed the encoding of the file somehow. If anyone has deeper knowledge of this issue please let me know in the comments. | stackexchange-wordpress | {
"answer_score": 34,
"question_score": 18,
"tags": "plugins, installation, permissions, nginx"
} |
Add a checkbox in plugin options page and make it actually work
My code:
function afi_checkbox_field_0_render( ) {
$options = get_option( 'afi_settings' );
?>
<input type='checkbox' name='afi_settings[afi_checkbox_field_0]' <?php checked( $options['afi_checkbox_field_0'], 1 ); ?> value='1'>
<?php
}
Now I want to check if the checkbox is checked then show a column, or else hide.
Somethink like:
function custom_columns($columns)
{ if ( the checkbox is checked)
$columns['the_column'] = 'The Column';
return $columns;
} else { (hide the column)
unset($columns['the_column'])
return $columns;
}
add_filter('manage_posts_columns' , 'custom_columns'); | It looks like your checkbox state is saved in `$options['afi_checkbox_field_0']`. You can check this setting anywhere using the following code:
$options = get_option( 'afi_settings' );
if ( ! empty( $options['afi_checkbox_field_0'] ) ) {
// Checkbox checked
} else {
// Not checked
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, admin, options"
} |
Add .html to Woocommerce permalinks
I'm redesiging a site for a client using Wordpress and WooCommerce and I need to add .html to all the woocommerce permalinks so they don't lose any SEO ranking when we go live with the site. Does anyone know of a way to achieve this? I've searched far and wide, and cannot find a good answer.
Thanks in advance for any assistance. | This is the simplest way to add `.html`, which involves overriding the default permastructure:
function wpse_178112_permastruct_html( $post_type, $args ) {
if ( $post_type === 'product' )
add_permastruct( $post_type, "{$args->rewrite['slug']}/%$post_type%.html", $args->rewrite );
}
add_action( 'registered_post_type', 'wpse_178112_permastruct_html', 10, 2 );
<
For categories:
function wpse_178112_category_permastruct_html( $taxonomy, $object_type, $args ) {
if ( $taxonomy === 'product_cat' )
add_permastruct( $taxonomy, "{$args['rewrite']['slug']}/%$taxonomy%.html", $args['rewrite'] );
}
add_action( 'registered_taxonomy', 'wpse_178112_category_permastruct_html', 10, 3 ); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "permalinks, woocommerce offtopic"
} |
Categories' hierarchy in URL
The posts in the website I'm currently working on have multiple hierarchical categories applied to each of them. For instance:
Source
- Books
-- Moby Dick
-- Sherlock Holmes
The permalinks are set as `/%category%/%postname%/`. However, the URL of a post does not include all subcategories - all I get is `site.com/source/books/*postname*`, even though the post in question has NOT been categories in Source, but only in Books + Moby Dick.
Could anyone help me figure out how to adjust this behaviour?
Thank you. | The permastruct `/%category%/%postname%/` will include the categories and subcategories in the URL **from top to first assigned child**. So, if you want the URL be `site.com/source/books/moby-dick/*postname*`, you have to assign the post only to "Moby Dick". Assigning the post only to "Moby Dick" category will still show the post under "source" and "books" category archives by default. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "categories, permalinks, url rewriting, hierarchical"
} |
Random post category URL
I'm trying to get a random post URL, only in current category. This is my code, this returns the URL category, :/
<?php
$current_cat = get_the_category();
$randomPost = $wpdb->get_var("
SELECT guid
FROM $wpdb->posts
WHERE post_type = 'post'
IN wp_terms = $current_cat
ORDER BY rand() LIMIT 1");
echo '<a href="'.$randomPost.'">
<div id="temporadas-dropdown">EPISODIO AL AZAR</div>
</a>';
?>
Can help me? | Pro tip - don't custom query unless you need to (you don't). And never use the `guid` field.
if ( is_singular() && $cats = get_the_category() )
$cat_id = $cats[0]->term_id; // Category ID for current post
elseif ( is_category() )
$cat_id = get_queried_object_id(); // Category ID for current archive
else
$cat_id = 0; // No cats
$posts = get_posts(
array(
'posts_per_page' => 1,
'orderby' => 'rand', // Here's our random magic
'cat' => $cat_id,
)
);
if ( $posts ) {
$random_url = get_permalink( $posts[0]->ID );
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "posts, categories, urls"
} |
error in wp_title on year archive - undefined index 00
In the year archive page in the title tag i get
Notice: Undefined index: 00 in wp-includes\locale.php on line 271
In the header.php i use:
<title><?php wp_title('|', true, 'right'); ?></title>
I even tried to use in functions.php
add_theme_support( 'title-tag' );
My question: is WordPress fault or my theme fault? I search on Google the notice and i found dozen of sites with this error on their titles. My temporary fix is to check if is year archive page and set the title. Any other ideas? | This is about letter "m".
Yoast SEO use $_GET['m'] in it's code and this creates a conflict.
Change your $_GET['m'] to e.g $_GET['mon'] and problem is solved. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "wp title"
} |
Add HTML to single post <head> tag
If I have developed a separate HTML page that I wish to include inside my Wordpress site what is the best way of including it? In this case it requires a javascript library or stylesheet that is not by default in my Wordpress theme that would need to be inserted in the tag.
I am aware of the following solutions:
iFrames:
* To match the site styling I would need to include every css from the theme in the iframe header.
* If the theme is updated with another script style sheet, this would not be updated in the iframe, maintenance could be arduous.
Editing the theme:
I could add into the various theme files along the lines:
is_single( 'page1' )
add_action( 'wp_head', 'extra_stuff' )
For each post/page I create or change I would have to change the theme files accordingly.
Ideally I would like to be able to do this from within the post editor
Are there any plugins that accomplish this? | I found the best solution was to add a custom field, `head`, and then build a short plugin to add the contents to the head tag:
add_action('wp_head', 'add_HTML_head');
function add_HTML_head(){
global $post;
if(!empty($post)){
// get custom field for 'head'
$headHTML = get_post_meta($post->ID, 'head', true);
if(!empty($headHTML)){
echo $headHTML;
}
}
}
I've packaged it up into a simple plugin. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "html, wp head"
} |
Authentication / login mechanism (non wp-admin)
I am developing a theme. I need to have a user login system, that allows users to see all contents of the application and interact with it **only after they login (not admin panel login).
I need to redirect all traffic at start** to a login.php page instead of wordpress "home" (page.php), if users are not logged in. Otherwise land in "home".
What is the right way to do that in wordpress without using plugins? | You can use the `wp_loaded` hook to push all non-logged-in traffic to the login screen. Note how I've passed `$_SERVER['REQUEST_URI']` to `wp_login_url()` \- this is passed as a URL parameter to the login page, and once a user successfully signs in, they'll be redirected back to the URL they were originally trying to visit.
function wpse_178177_redirect_to_login_if_guest() {
if ( ! is_admin() && ! is_user_logged_in() && $GLOBALS['pagenow'] !== 'wp-login.php' ) {
wp_redirect( wp_login_url( $_SERVER['REQUEST_URI'] ) );
exit;
}
}
add_action( 'wp_loaded', 'wpse_178177_redirect_to_login_if_guest' ); | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 3,
"tags": "theme development, redirect, login, homepage, authentication"
} |
List subcategory on taxonomy term page
On WooCommerce I am using the archive-product.php template page. I want to show a list of the sub-categorys from the displayed category.
So as the user changes category the list of subcaegories will change to match.
I can get the sub categories for a specific parent category, but I am stuck getting something like `if($cat->category_parent == $this)`
The code I am using to get subcategorys listed for parent Id=9
<?php
$args = array(
'taxonomy' => 'product_cat',
'orderby' => 'name'
);
$all_categories = get_categories( $args );
foreach ($all_categories as $cat) {
if($cat->category_parent == 9) {
$category_id = $cat->term_id;
echo '<a href="'. get_term_link($cat->slug, 'product_cat') .'">'. $cat->name .'</a>';
}
}
?>
But how do I make it dynamic so each category will show its own subcategories? | You can make use of `get_term_children()` instead of `get_categories()`
You can try something like this
$term = get_queried_object();
$term_id = $term->term_id;
$taxonomy_name = $term->taxonomy;
$termchildren = get_term_children( $term_id, $taxonomy_name );
echo '<ul>';
foreach ( $termchildren as $child ) {
$term = get_term_by( 'id', $child, $taxonomy_name );
echo '<li><a href="' . get_term_link( $term, $taxonomy_name ) . '">' . $term->name . '</a></li>';
}
echo '</ul>'; | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "custom taxonomy, terms"
} |
Registration Plugin - Recaptcha integration
Good Day Everyone,
I'm currently writing a new plugin for Registration, I intend to actually share that Registration Plugin, but I would like to integrate reCaptcha into it.
From what I understood reCaptcha is actually website related; So if I want to integrate it in my plugin I would need to ask the user/admin of the websites to actually enter their website key to "activate" it?
Or did I understood that wrong? | Your plugin users will need to register their site at < to use the reCAPTCHA API. Once registered, users will need to provide you with their Site Key and Secret Key.
The Site Key allows you to display the reCAPTCHA on your Registration form. The Secret Key is used to confirm the reCAPTCHA field input. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "security"
} |
Help diagnosing scheduled post problem with transition_post_status
I've messed with trying to get scheduled posts to fire a function for months and finally stripped things down to the following code to see what is happening. The problem is that a scheduled post will not show the wp_die.
add_action( 'transition_post_status', function ( $new_status, $old_status, $post ) {
if( 'publish' == $new_status && 'publish' != $old_status ) {
wp_die('STOP');
}
}, 10, 3 );
If I simply immediately click on post then the STOP shows but a scheduled post shows nothing and will publish. I've also tried simply wp_die($post); to see what is returned on a scheduled post and there the wp_die isn't fired.
Even forcing this to 'future' == $old_status does not work.
How can I diagnose why this isn't firing for scheduled posts?
I've tried var_dump as well. | By default `add_action()` only passes one parameter, not all three. Change your function to:
add_action( 'transition_post_status', function ( $new_status, $old_status, $post ) {
if( 'publish' == $new_status && 'publish' != $old_status ) {
wp_die('STOP');
}
}, 10, 3 );
**Edited to add:**
The `transition_post_status` hook fires after the post transition from future to publish has occurred, and calling wp_die() will not display 'STOP' for scheduled posts. Instead you will just prevent the remaining actions in `wp_transition_post_status()` from being processed.
Future posts are published with background scheduled events via wp_cron, so calling a function like `var_dump()` or `print_r()` will not be useful for debugging. Instead try using `add_option()`, `wp_mail()`, or XDebug bookmarks: jetbrains.com/phpstorm/help/configuring-xdebug.html | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "posts"
} |
List Available Templates for Current Theme in a Plugin
I am new to Wordpress as of last week and am having trouble understanding some things. I have created a plugin that allows for the dynamic creation of multiple pages.
There is one thing that I cannot figure out how to do. I want to display a list of the available templates in a dropdown, so that the user an assign that particular template to the pages they are creating.
Is there a wordpress function built in that allows for this. If not, can anyone guide me towards where to start on this. Thanks in advance. | The available templates are returned by `get_page_templates()`, which mostly forwards it to current theme's object.
There is also more specialized `page_template_dropdown()`, which you might be able to use in your form. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development"
} |
How do I turn this form into a search form?
Hi I have an expanding search form inside the wordpress header and would like to make it work with my theme?
<
<div class="search">
search
<input type="text" />
</div> | Please try this ,
<form name="searchBox" action="<?php echo get_bloginfo('url'); ?>" class="search-form" method="get" role="search" >
<input type="text" name="s" class="searchBox" placeholder="search" value="<?= $_GET['s'] ?>" required />
<button type="submit" class="searchBtn" >search</button>
</form> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "search, navigation"
} |
Proper way to update the slug of a taxonomy using register_taxonomy?
What is the best way to update the slug of a custom taxonomy that is registered by a plugin? I want to know the minimal amount of parameters for this or if i need to go and copy paste all of the original parameters. This seems like it can be error prone if the plugin has an update. The codex says you will overwrite the original when using register_taxonomy so is there a better way to do this or a different function? | `register_taxonomy` triggers the action `registered_taxonomy` immediately after it's registered, which gives you the arguments it was registered with. As long as the taxonomy key doesn't change, you can hook that action, modify the arguments, then re-register it.
function wpd_update_taxonomy_args( $taxonomy, $object_type, $args ){
if( 'plugin_tax' == $taxonomy ){
// remove this action so we don't create an infinite loop!
remove_action( current_action(), __FUNCTION__ );
// change arguments
$args['rewrite'] = array( 'slug' => 'foobar' );
// re-register
register_taxonomy( $taxonomy, $object_type, $args );
}
}
add_action( 'registered_taxonomy', 'wpd_update_taxonomy_args', 10, 3 ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom taxonomy, taxonomy, register taxonomy"
} |
Adding Edit subnav link to Custom Buddypress Profile Tab
I've created a custom tab to my buddypress user profiles called 'goals'
It displays xprofile fields, I just need to know how to make a dynamic link on the subnav that points at the 'goals' xprofile edit link tab which for example would look like
> www.dev.globalsportcoach.com/members/USERNAME/profile/edit/group/8/
The subnav is currently being generated via the following, however I've tried a few variations of the link parameter however can't get it to structure properly.
bp_core_new_subnav_item( array(
'name' => 'Edit Goals',
'slug' => 'edit-goals',
'parent_url' => 'goals',
'parent_slug' => 'goals',
'screen_function' => 'false',
'position' => 50,
'link' => get_option('siteurl') . '/profile/edit/group/8/'
) ); | Use `bp_core_get_user_domain($user_id)`. This will give you the url part up to the username (with a slash at the end).
Try something like the following:
$user_id=bp_displayed_user_id();
$link=bp_core_get_user_domain($user_id)."profile/edit/group/8"; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "links, buddypress"
} |
Show Image Size as Dragging it Larger or Smaller
I've searched everywhere for this, but no luck! I think I must be hallucinating.
I thought previous versions of Wordpress displayed the size of the images in the visual editor as you dragged them to be smaller or larger. As in, you would pull the corner of the image inward or outward, and the "live" size of the image would show above the image as you dragged it. In other words you could see what size the image is as you make it smaller or larger, and that size is what gets printed in the HTML.
Does anyone know if this "live image size display" exists in Wordpress' coding, or if there's a way to get something like that working? Am I hallucinating? Thank you! | This is a screencast from my WordPress 4.1 install:
!live image info
where the image `width x height` info is visible while we resize the images.
This comes out of the box and no magic needed ;-) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "images"
} |
Can't Install Child Theme "The parent theme is missing. Please install the "Default" parent theme."
This is my first time installing a child theme and I ran into some errors
Here' the style.css
/*
Theme Name: WD TechGoStore-child
Theme URI:
Description: Commerce Template
Author: WPDance Team / WPDance.com
Author URI:
Version: 1.0.3
Template: Default Template
Tags: one-column, two-columns, three-columns, left-sidebar, right-sidebar, flexible-width, custom-menu, full-width-template, rtl-language-support, sticky-post, theme- options, translation-ready
License: GNU General Public License v2 or later
License URI:
*/
Here's the error:
> The parent theme is missing. Please install the "Default" parent theme.
I've already tried several names for the "Template" but don't know which one should be there as my theme only uses the default template.
Any help would be appreciated. | Change this line: `Template: Default Template` to `Template: wp_techgostore-theme-package`
As per the WordPress Codex,
> The Template line corresponds to the directory name of the parent theme | stackexchange-wordpress | {
"answer_score": 11,
"question_score": 1,
"tags": "themes, child theme"
} |
If ACF meta_key has meta_value
I have an ACF field (options) that contains a list of options:
Blue
Red
Green
I would like to echo the option selected, ie:
if(get_field('blue') == true) {
echo "You have selected the color Blue";
} | While writing out this troubling question, alas! the answer did fall from the heavens and presenteth itself unto me:
$meta = get_post_meta( get_the_ID(), 'options');
if(in_array('blue',$meta)) {
echo "You've selected blue, punk!";
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "post meta"
} |
Stop Plugin Enumeration
Is there any way to stop plugin enumeration? I have tried Acunetix WP Security plugin, It seems to work but Yoast SEO plugin is still enumerating. Any plugins or code modifications are appreciated.
Thanks in Advance :) | There is no need to stop "plugin enumeration", just use plugins from a good home and make sure you have restrictive file permission setting on your server.
In theory you can use htaccess to mask the original location of the plugin on the disk and write some code to serve any JS and CSS file as if they are located at some other directory, but this depends on the way the plugin works, some plugins might work while some might fail.
But in the end if a plugin gives admin credentials to everyone that surfs to example.com/?admin=me then the bad guys don't even need to enumerate the plugins on your site, they will just go directly to that url. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugins, security, privacy"
} |
Wordpress 4.1 update broke theme
How do I roll back WP install? Sometime in the last 20 minutes, my website updated to 4.1, which swapped to the 2015 theme and refuses to let me use my template because:
The following themes are installed but incomplete. Themes must have a stylesheet and a template.
Name Description
blankslate/css Template is missing.
This is so very very not cool. Please help! | Most of these errors are caused by damaged or corrupt theme files.
> Upload theme files/directory again and you will be fine.
Strange things happen sometimes, that's why it's always recommended to keep a backup of your WordPress files and database before updating. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "installation, upgrade"
} |
wpautop - disable <br> tags, keep <p> tags
I write My articles in Emacs and they end up having tons of newlines, with double newlines to separate paragraphs. Ideally, I want wordpress to work like markup does, meaning it ignores single line breaks but adds paragraphs when a double newline is met.
Unfortunately, disabling wpautop makes Wordpress ignore both single and double newlines. I want to be able to use the function in a way that ignores `<br>` tags for single lines but adds `<p>` tags when two newlines are met. | wpautop can ignore the linkebreaks if you use wpautop( $content, false ); To pass a parameter to wpautop via add_filter, use an anonymous function.
This snippets seems to work for me if I add it to my theme's functions.php:
remove_filter( 'the_content', 'wpautop' );
$br = false;
add_filter( 'the_content', function( $content ) use ( $br ) {
return wpautop( $content, $br );
}, 10 ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "functions, editor"
} |
EM in CSS different size on wordpress then elsewhere
I am creating a Blog, and custom Theme, using Wordpress for my existing site. I am trying to get it to match exactly the look and feel of the main site, so I logically just copied over all the CSS...
Most of my size definitions are based on em. I am seeing a very large size discrepancy on elements which have em definitions for their size.
Live examples: Home page: < Blog: <
You can see the difference clearly if looking at the header and footer. The header/foot height is defined by em, as well as the text size, and padding of the items which is off for the navbar links and left footer text.
I am working off an Underscores template, and found the only relevant CSS below, which all looks legit.
color: #404040;
font-size: 16px;
font-size: 1rem;
line-height: 1.5;
1. Why is my em sizing on the Wordpress site significantly smaller than it should be? | From the spec: "EM is Equal to the computed value of the ‘font-size’ property of the element on which it is used."
You have a different font-size value between the two URLs you provided (14px and 10px respectively).
Line 273 of your style.css file is replacing the default Bootstrap font-size for the body element (line 5 of bootstrap.min.css). | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "themes, css"
} |
Error 404 on wp-includes directory
I'm having a lot of 404 errors for files which are supposed to be in the /wp-includes/ folder.
This makes some part of the website and the admin panel unusable (in the edit post page it won't even load tinymce editor).
I have the latest version of wordpress 4.1 and some plugins that I'm already using on other websites.
I've tried to disable theme and plugins, reupload wp-admin and wp-include via ftp but nothing changes. Also uploaded a clean .htaccess, and nothing. Same by reverting to an older version of wordpress. Any idea about what can be a solution? Looking in the ftp, the folder is there, and file permissions are set properly(755 folder, 644 files). But everything in it is unreachable from the broser.
The website is: < you can see that it fails to load jquery library (i've included it manually in the header as a temporary solution to make the website work) | I've found what was the problem. An old version of Slider Revolution plugin, that probably was hacked.
I upgraded the plugin to the latest version and now everything is fine. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "404 error"
} |
Blank space at beginning of <title> tag?
The HTML output of all my WordPress pages has a blank space at the beginning of my `<title>` tag. You can see the effect here.
My header template contains this:
<title><?php wp_title(''); ?></title>
And roduces this:
<title> FAQ</title>
Any ideas on why this is happening? | It looks like your _site's title_ is empty. Fill it out or try for example:
add_filter( 'wp_title', function( $title )
{
return trim( $title );
} );
to remove the blank space in front.
For your setup, the following part of `wp_title()` is responsible for the blank space:
$title = $prefix . implode( " $sep ", $title_array );
So when you're on a single page, like `FAQ`, this will give you:
$title = ' ' . implode( " ", array( 'FAQ' ) );
or
$title = ' FAQ'; | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 1,
"tags": "php, templates, html, title"
} |
WPDB for post count on post
I figured out how to show the count of a custom post type on author.php . I am trying to display the stats on their custom post as well. The same query does not work. How can I show the amount of custom post on the custom post themselves for users? My query below works on author.php not the post types themselves and I do not understand.
<?php
global $wp_query;
$curauth = $wp_query->get_queried_object();
$post_count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = '" . $curauth->ID . "' AND post_type = 'campaigns' AND post_status = 'publish'");
?> | The problem you are having is that get_queried_object returns results based on the query that was run.
On author.php, the queried object was an author.
On single.php, page.php, or any custom post type template, the queried object will be the post, not the author.
This means that if you want to use `$wp_query->get_queried_object();`, you will have to be aware of what kind of object you re grabbing ... and possibly do other things if your object is a post or a page.
e.g.
$post = $wp_query->get_queried_object();
$author_id = $post->post_author;
$post_count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = '" . $author_id . "' AND post_type = 'campaigns' AND post_status = 'publish'");
For term pages, post archive pages, etc., you might need to do such inside of the loop by grabbing the current post object, reading the author, and then grabbing that authors counts. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, wp query, wpdb"
} |
Is there a way to make a pure vanila page of just HTML/CSS/JS
Bit of a odd question. I want to be able to host example simple websites on my Wordpress Site. These "simple" sites would just consist of client side code.
Is there a way to create a page which just uses these files, possible a plugin I am unaware of?
Thank you. | I've done this in the past by using custom page templates.
Basically, there are two ways to create a custom page template.
1. You can create a file in your themes directory and name it `page-vanilla-html.php`.
2. You can create a file and name it whatever you want (for example `vanilla-html.php`). You just need to include a template description at the top of the file:
<?php
/*
* Template Name: A Vanilla HTML/CSS/JS Custom Page Template
* Description: This template is nothing but vanilla HTML/CSS/JS!
*/
?>
Once you've created the custom template, you simply create a new page within Wordpress. If the name of the page is "Vanilla HTML" it will search for a file named `page-vanilla-html.php` and load it automatically. If you used the second method, you can select the template from the drop down on the right side of the page creation screen. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "plugins"
} |
How to change the title url on the edit post screen?
I searched in various places and am battling to find the correct place or terms used for the following.
I am only using posts as an example.
When you view all posts in wp-admin you get the title of the post and below it the Edit, Quick Edit, Trash and Preview links. By using the post_row_actions action hook I can change the links below the title but not the link on the title itself.
Are there an alternate way to change the link on the post title to open a different url? or can I change it with the same hook?
I am developing front-end content management screen and want to point all edit links to point to the front of the website.
Many thanks :) | Use `get_edit_post_link` filter.
add_filter('get_edit_post_link', 'get_edit_post_link_178416', 99, 3);
function get_edit_post_link_178416($link, $post_id, $context) {
$scr = get_current_screen();
if ($scr->id == 'edit-post' && $context == 'display') {
return '
} else {
return $link;
}
}
You can see it's used here | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 1,
"tags": "posts, wp admin, row actions"
} |
Trying to disable slider for WooCommerce price filter
I'm currently working on an e-commerce site that uses WooCommerce, and the client wants to change the price filter from the existing range slider to the two inputs. By default, WooCommerce creates it as two inputs, then uses jQuery UI to replace it with a slider to make it accessible.
Now, I can do this by commenting out the appropriate `wp_enqueue_script` call in WooCommerce itself, but this will obviously get overwritten when WooCommerce gets updated.
As far as I can tell, the following should work when inserted into the `functions.php` for the theme:
function remove_slider() {
wp_dequeue_script( 'wc-price-slider' );
}
add_filter( 'wp_enqueue_scripts', 'remove_slider' );
This is consistent with what I've seen in quite a few blog posts that turned up in a Google search. However, it's just not working. Any idea what I need to do to achieve this? | This script is localized and registered, so you're going to need to use wp_deregister_script() instead of wp_dequeue_script(). Also, you need to use the function add_action() instead of add_filter() for this. Think of add_action as a way to inject run-able code into an existing function and think of add_filter as a way to manipulate the returned output of an existing function.
function remove_slider() {
wp_deregister_script( 'wc-price-slider' );
}
add_filter( 'wp_enqueue_scripts', 'remove_slider' );
the above works on my current install. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "woocommerce offtopic"
} |
Is there any difference between below WP_Query code snippets?
Below code return the same results. Is it any difference between them and if it is then which one is better?
# code snippet 1:
$args = array(
'post_type' => 'product',
'meta_key' => 'location',
'meta_value' => 'Melbourne'
);
$query = new WP_Query( $args );
# code snippet 2:
$args = array(
'post_type' => 'product',
'meta_query' => array(
array(
'key' => 'location',
'value' => 'Melbourne'
),
),
);
$query = new WP_Query( $args ); | There is no difference in terms of the "final" query. The former was the "old" way of querying post meta, before `WP_Meta_Query` was introduced with support for more complex queries.
`WP_Query::get_posts()` now simply translates `meta_key/value` arguments into the new format with `WP_Meta_Query::parse_query_vars()`.
Use whichever format you feel suits best for the task. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query, meta query"
} |
WP_Query search for whole words
I'm searching for science related terms. Here's what I need my query to do. If someone searches 'bio', they should not get results for terms 'biology' but they should for 'bio science'. I need the query to return results for the whole word. Any suggestions are appreciated. Thanks!
Here is my code:
$queryArgs = array(
'post_type' => 'faculty',
'posts_per_page' => -1,
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'proposed_keywords', // name of custom field
'value' => $keyword, // matches exaclty "123", not just 123. This prevents a match for "1234"
'compare' => 'LIKE'
)
)
); | You're gonna need regular expressions to accomplish that.
First of all, you need to change `'LIKE'` to `'RLIKE'` (or `'REGEXP'`).
Second, replace `$keyword` in `'value'` with a regex that involves word boundaries.
Like so:
$queryArgs = array(
'post_type' => 'faculty',
'posts_per_page' => -1,
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'proposed_keywords', // name of custom field
'value' => "[[:<:]]$keyword[[:>:]]", // matches exaclty "123", not just 123. This prevents a match for "1234"
'compare' => 'RLIKE'
)
)
); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "wp query"
} |
Removing backstretch image from pages/posts
Homepage has a backstretch image which is also active throughout the site on posts and pages. How can I keep the backstretch on the homepage but hide it on posts or pages? pulled this from the functions.php thinking this might be where I'd need to start:
//* Load scripts only if custom backstretch image is being used
if ( ! empty( $image ) ) {
wp_enqueue_script( 'theme-backstretch', get_bloginfo( 'stylesheet_directory' ) . '/js/backstretch.js', array( 'jquery' ), '1.0.0' );
wp_enqueue_script( 'theme-backstretch-set', get_bloginfo( 'stylesheet_directory' ).'/js/backstretch-set.js' , array( 'jquery', 'theme-backstretch' ), '1.0.0' );
wp_localize_script( 'theme-backstretch-set', 'BackStretchImg', array( 'src' => str_replace( 'http:', '', $image ) ) );
}
} | Add a conditional to the existing if-statement checking for `is_front_page()` (or `is_home()`, depending on your needs):
if ( ! empty( $image ) && is_front_page() ) { | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, responsive, custom background"
} |
Blank <title> on static home page?
The `<title>` of each page on my site shows correctly with the following code:
<title><?php wp_title(''); ?></title>
But on my home page, which is set to a static page called 'Home', the `<title>` attribute is blank. The HTML for 'Home' page looks like this:
<title></title>
The settings for the 'Home' page has 'Home' as the page title, but it doesn't show on the actual page output. Any idea why? The issue can be seen here. | From the Codex
`If you are using a custom homepage with custom loops and stuff or a custom front-page, you will have an empty wp_title. Here goes a neat hack to add the description/tagline at the wp_title place on homepage:`
add_filter( 'wp_title', 'baw_hack_wp_title_for_home' );
function baw_hack_wp_title_for_home( $title )
{
if( empty( $title ) && ( is_home() || is_front_page() ) ) {
return __( 'Home', 'theme_domain' ) . ' | ' . get_bloginfo( 'description' );
}
return $title;
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "php, templates, html, title"
} |
Does WordPress count as a means to learn web development?
I'm learning to make themes in WordPress, basically with CSS only. I don't feel like I'm learning actual web development (front end). I don't see how I can incorporate JS into themes, because it seems that WordPress does all the stuff for you (such as the drop-down navigation menus).
I know this is a badly written question. Basically, can WordPress be used as a means to learn overall front end development, or should I try it some other way? | Yes and no.
WordPress is inherently web content management system. Whatever you do with it _is_ web development since end result is, well, a web site.
However not all of WordPress is web development. Not all of web development is something that you typically do in WordPress.
As you grasped WP is strong at back–end and contains immense amount of functionality, as well as means to produce a lot of markup server-side. This is _good_ since it saves you from all that work.
But the other side of the coin is that WP is kind of set in its ways. It is a legacy framework and “newer” (or even years old really) techniques (such as dedicated template languages, JS frameworks, and so on) are often under–explored in it.
In a nutshell starting with WordPress development _does_ expose you to considerable amount of generic web development concepts (depending on what exactly you do with it), but it won't be exhaustive and at some point you will have to look beyond WP to make further progress. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "theme development"
} |
Must filter functions receive all arguments passed to them?
I'm writing a filter function to redirect logins:
function my_filter_func( $redirect_to, $requested_redirect_to, $user) {
// My code.
}
add_filter( 'login_redirect', 'my_filter_func', 10, 3 );
The filter hook in the template file is:
$redirect_to = apply_filters( 'login_redirect', $redirect_to, $requested_redirect_to, $user );
As you can see, `$redirect_to`, `$requested_redirect_to`, `$user` are passed to my filter function. My filter function receives these and I can use them in my function's code.
**My question:**
Must my function receive all 3 variables? Or can I do this:
function my_filter_func( $redirect_to ) {
// My code.
}
add_filter( 'login_redirect', 'my_filter_func' ); | Your function does not have to accept all arguments, you can not specify the number of accepted arguments and it will default to passing just the first.
You can also specify any number up to and including the total number of arguments. For example if you only need the first 2, this will also work:
function my_filter_func( $redirect_to, $requested_redirect_to ) {
// My code.
}
add_filter( 'login_redirect', 'my_filter_func', 10, 2 );
What you can't do is use more arguments than what you specify in your `add_filter` call. For example, this will generate a missing argument 2 warning:
function my_filter_func( $redirect_to, $requested_redirect_to ) {
// My code.
}
add_filter( 'login_redirect', 'my_filter_func' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, functions, filters, hooks"
} |
How to Prove Ownership of plugin
So I'm considering writing wordpress plugins to sell. Apparently distributing these type of plugins requires you to hand over the source code to the client. What would happen if one of the clients claims ownership of my plugins and starts selling them. How would I prove ownership of my plugin?
For example in VB.Net project your code will be compiled so the end user will not have access to the source. So you can prove ownership by showing your code to the court, while he does not have access to it. | You don’t sell the code, you sell support and automatic updates. If your plugin is successful, some people might try to claim the ownership … that doesn’t really matter, they will never be relevant for your business.
If you want to get a legal proof that you are the owner, develop your code with Git from the very first line on, and use signed commits. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -1,
"tags": "plugin development, copyright"
} |
Why won't this wpdb get_results query return results?
Having trouble with this query. It returns an empty array even though I know the variables are correct and that multiple rows exist in the database that match.
$results_a = $wpdb->get_results(
$wpdb->prepare("SELECT *
FROM $wpdb->custom_table
WHERE 'FK_show'=%d
AND 'season`=%d",
$FK_show,
$season),
ARRAY_A
); | When the query was done using ~ (tilda) quotes around columns in the SQL instead of the ' it worked. It has something to do with the collation of my tables in MySQL, I believe. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, mysql, wpdb"
} |
Custom Taxonomy Terms in Menu lead to which page?
Hello All I was wondering if someone could help me out. I have created a custom post type along with a custom taxonomy. In this custom taxonomy I have created custom terms through the wp dashboard. I have added these terms to my Nav menu when I click on these terms in goes to a page. My question here is is that page the archive.php? How would I style that page how I want? Thanks | It's the template taxonomy.php, and some variants: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, custom taxonomy, taxonomy, terms"
} |
Theme options are they necessary
So I have decided to use wordpress for a site. But just as I begun I realized that I might need options. Things as simple as logo, favicon and possibly some parallax settings.
Is it necessary to have options or can I set the logo by just getting the uploads/images path and setting it to logo.jpg.
Then for say the parallax just categorizing pages and based on category use a specific section.php file to perform whats necessary?
I am new to creating themes in wordpress so if its not necessary I would prefer to not use options unless its easier than it looks. So far I got the 'Options Framework' plugin but am not sure how to use it exactly. | If you are developing the theme for yourself to use I don't see any reason for adding options if you don't want to/know how. If you are planning on distributing/selling your theme though, you might want to consider adding some options for your customers to change the settings and customize the theme.
I'd say that options are nice to have, but not necessary at all. If you are new to WordPress, learn how it works first. Then add options down the road if you feel that it would add some value for your site. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme options, options, plugin options"
} |
Changing WP login credential
How would I edit the login credential so that I can add phone number as a part of login credential?
For example, an user will be able to login using either phone number, email or username.
Thanks! | There is a plugin that I use called 'username' just search from you're WP-Admin Plugin Search and type 'admin username change' & _username_ & a bunch of other Admin & User Username Plugin Change Plugins will appear. I cannot give you the full answer if you are looking for 3 fields eg: - Username \- eMail \- Phone #
Though I suggest finding the plugin that wull allow you to change usernames for users & admin from this search (which do show up), and after choosing find a coder who can add the extra lines of code to the Plugin.
P/S - Searching Google for a Username Login Changer Plugin would also benefit in finding the right one (simplest one for you're needs) to 'modify with the required PHP code' and can be posted here if there is no a less complicated PHP only MOD someone can help you with wi/out a plugin. This is just from my similar multi-login type experience. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "login"
} |
'is_author()' logic in widget for author only
So, I have a widget that I only want to show it to the page author.
I used the following logic: is_author()
However it does not seem to work (it shows non-author)
Am I using this logic right?
Any suggestions?
Thank you | is_author() is only for Archive pages. Quote from the Codex:
> is_author() checks if an Author archive page is being displayed
So viewing a single Post or Page isn't going to get a TRUE from is_author().
I think you'll want something more like this:
global $post,$current_user; // get the global variables to check
get_currentuserinfo(); // get current user info
// Now check if the author of this post is the same as the current logged in user
if ($post->post_author == $current_user->ID) {
// do code here
}
I hope this helps. :)
EDIT #1: Shortened code version.
// Check if the author of this post is the same as the current logged in user
if ( $post->post_author == get_current_user_id() ) {
// do code here
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "widgets"
} |
How to rename Profile link in wp-admin page
i want to modify the profile link in wp-admin to **Settings**
I want to rename the 3 below things to Settings which are marked in red
!enter image description here | Changing the menu title is easy enough, you just need to place this in your **functions.php** file -
add_action('admin_menu', 'my_change_admin_menu');
function my_change_admin_menu(){
global $menu;
$menu[70][0] = 'New profile menu title';
}
However, you cannot change the title of this page via WordPress, not the update button text, but if you **really** need to do so you can use some jQuery -
jQuery(document).ready(function($){
$('#profile-page > h2').text('New profile menu title');
$('#profile-page input#submit').attr('value', 'New updatew button text');
}); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "admin menu"
} |
To remove default dashboard items and add quick draft widget for custom post type
i want to remove screen options from wordpress admin panel and remove default dashboard items and add quick draft widget in dashboard for custom post type "gallery". !enter image description here | You can remove the Screen Options with the 'screen_options_show_screen' filter.
function myplugin_disable_screen_options( $show_screen ) {
// Logic to allow admins to still access the menu
if ( current_user_can( 'manage_options' ) ) {
return $show_screen;
}
return false;
}
add_filter( 'screen_options_show_screen', 'myplugin_disable_screen_options' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "wp admin"
} |
Post formats and template hierarchy
I want to use post formats but the theme (WP-Bootstrap by 320Press) on which my current template is based doesn't make use of the content.php template, only single.php.
Is it possible to edit the template hierarchy so that you can append formats to the single template (single-image.php, for example)? Alternatively, if this is best avoided, can anyone suggest another workaround? | It is easy to make this work if your theme don't support post formats
* Create a child theme
* `add_theme_support` for post formats
* Remove the loop from your template files and add replace it with `get_template_part( 'content', get_post_format() );`. Your template should look like this
if ( have_posts() ) { // <- Not necessary in single.php
while ( have_posts() ) {
the_post();
get_template_part( 'content', get_post_format() );
}
}
* Everything else should go into a new file which should be called `content.php`
* Create a new file called `content-image.php` and add the loop in there and modify as needed
* When a post is assigned the `image` post format, `content-image.php` will be used inside single.php to display the image posts
Look at one of the bundled themes how to exactly make use of post formats | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "post formats"
} |
$wpdb->query can't insert data
I Write Code to Save data in the Wordpress database table (table name is wp_fafa)
But Can't Save data in
$qry = $wpdb->query( "INSERT INTO `wp_fafa` (titile,liveprice,changing,lowest,topest,time) VALUES ('" . trim($row->item(0)->nodeValue) . "','" . trim($row->item(2)->nodeValue) . "','" . trim($row->item(4)->nodeValue) . "','" . trim($row->item(6)->nodeValue) . "','" . trim($row->item(8)->nodeValue) . "','" . trim($row->item(10)->nodeValue) . "')");
$wpdb->query($qry); | The following code will properly store data in `wp_fafa`:
$wpdb->insert( $wpdb->prefix . 'fafa',
array(
'title' => trim($row->item(0)->nodeValue),
'liveprice' => trim($row->item(2)->nodeValue),
'changing' => trim($row->item(4)->nodeValue),
'lowest' => trim($row->item(6)->nodeValue),
'topest' => trim($row->item(8)->nodeValue),
'time' => trim($row->item(10)->nodeValue)
),
array(
'%s',
'%s',
'%s',
'%s',
'%s',
'%s'
)
); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "database, query, wpdb"
} |
Can't add any menu items anymore, server related
_Unsure if this fits here, but hopefully it does._
So I'm having an issue that I can't add any menu items to a custom menu anymore. At this very point I can verify that it's server related, since this issue is appearing now on multiple Wordpress installations, even a complete fresh one.
For the record: I have tested it, as said, on a fresh installation with the basic theme, newly downloaded Wordpress, no configuration changes, etc.
Each installation on the server has it's own wp-config, .htaccess and php.ini file and there are non in the root (`public_html/`), so neither of those can't be the issue.
I'm running a Ubuntu 14.04 VPS.
Anyone got a suggestion? | While it is a guess, rather than certainty, the issues with menus typically boil down to following — working with them involves submitting large and complicated POST requests to server.
And what on server has issue with large and complicated POST requests? Security software!
The first item to check in such case is usually going to hosting support and asking if they are:
* using anything like mod_security
* does anything show up in security logs | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "menus, server"
} |
get_the_foo() in the loop - does it perform another query?
I'm unclear on the `get_the_foo()` style of functions, for example `get_the_permalink()`.
My main question is: when this is performed in The Loop, is another SQL query executed (besides the original `WP_Query()`)?
But: if performed by itself, e.g. `get_the_permalink($someId)`, a query _is_ executed, correct? | Query results for posts, terms, and metadata get placed in cache. If a function is called that accesses data from previously queried objects within the same request (or you're using a persistent cache mechanism that maintains data across requests), it will not trigger another query and will instead fetch the data from cache. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "loop, query, performance"
} |
How do I include drag-and-drop in a plugin?
I want to build a WordPress plugin that will allow users to add and delete fields from a custom post type. I want them to be able to do this with drag-and-drop, just like they add widgets to a sidebar. That is to say, the plugin will have a group of allowable fields, and the users will drag and drop those fields into a box to allow them to configure the fields in a custom post type.
Are there WordPress functions that allow developers to do this? Is there a tutorial anywhere that shows how to do this?
Thanks! | WordPress has a few of these libraries that come with core, you can view the list here: Default Scripts Included and Registered by WordPress. What you're looking for is Draggable, Sortable, and in your case Droppable.
You would use `wp_enqueue_script()` to add it like so:
`wp_enqueue_script( 'jquery-ui-droppable' );`
WordPress registers these scripts using a Handle which you can use to add them, the list of Script Handles can be found in the first link above. You would still need to hook into the admin panel and add the script:
function load_custom_wp_admin_style() {
wp_enqueue_script( 'jquery-ui-droppable' );
}
add_action( 'admin_enqueue_scripts', 'load_custom_wp_admin_style' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "custom post types, plugin development"
} |
Front-end CSS Library for plugin
I'm looking for a CSS library that can style elements I display on the client-side (front-end) of a wordpress website. The CSS library needs to be able to work with most of the wordpress themes, which means it just has a list of classes I can use, and doesn't alter the themes' global style (see below for explanation).
The problem with the libraries I've come across is that they alter the global style of a theme. For example they style the body tag with a background color, they edit the fonts and sizes of h1, h2, h3 etc tags. Another part of the problem is _normalize.css_ , it tends to break themes.
So far I've tried:
* Bootstrap
* Bootflat
* Foundation
* Pure-io (too few styling options)
* Topcoat
In short: I'm looking for a CSS library which doesn't alter any elements unless I attach a class to those elements. This way I can build a plugin which doesn't break theme styles.
Are there any recommendations? | Achieving unaltered style via plugin for multiple themes is pretty difficult to achieve.
How about this?
Use any library among these e.g. Bootstrap in your plugin and then remove/comment the global properties from them.
Since you will be author of the plugin, you can repeat the same thing in your plugin before releasing next update. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, css, front end, library"
} |
"Maximum function nesting level of '100' reached" after adding a new filter
I am trying to filter my post title for a specific page and when a form is submitted on that page , for this I am trying to filter my title . Here is the code
function filter_title_after() {
$current_page_id = get_the_ID();
if($current_page_id == 58 && !empty($_POST)){
$title = "Congratulation";
} else {
$title = the_title();
}
return $title;
}
add_filter( 'the_title', 'filter_title_after');
After adding this filter , I am getting an error ""Maximum function nesting level of '100' reached, aborting!
I have already looked several stackexchange question , but none of the came to any help
wp_insert_posts Fatal error: Maximum function nesting level of '100' reached, aborting! Problem:Save Several Duplicate posts in The Database and then Error nesting level of '100' reached | `the_title()` calls your function again. If you want to avoid that, remove the callback inside of your function:
function filter_title_after() {
remove_filter( current_filter(), __FUNCTION__ );
// the rest of your code.
But you shouldn’t call `the_title()` in your function at all: it **prints** the title – this is not what you want – and you get the original title and ID already as an argument from WordPress. Use it.
Also, testing for POST requests should be done by checking `$_SERVER[ 'REQUEST_METHOD' ]`.
function filter_title_after( $title, $post_id ) {
if ( ! is_singular() )
return $title;
if ( 58 !== (int) $post_id )
return $title;
if ( 'POST' !== $_SERVER[ 'REQUEST_METHOD' ] )
return $title;
return "Congratulation";
}
add_filter( 'the_title', 'filter_title_after', 10, 2 ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "php, filters, title, fatal error"
} |
How to use `wp_insert_post()` and `get_permalink()` functions?
I'd like my script to post an article to Wordpress site automatically.
Looks like Wordpress's `wp_insert_post()` function is what I need. But if I would include `wp-includes/post.php` file into my script the function `add_action()` (placed in `wp-includes/plugin.php`) will be needed.
The same story to `get_permalink()` function.
So I will probably need to include more and more files and I don't really like it as I'm not sure that everything will be OK with this mass including.
Probably Wordpress has some let's say 'header' file?
I tried also to include `wp-blog-header.php` file which looks like including all needed functions (at least my script stops to argue for using of unknowing functions) but it sends headers and probably can do something what I'm not expected.
**Disclaimer:** I have read wp_insert_post page on Codex and make some network search. But I still don't have an answers. | You can include wp-load.php (in the root Wordpress directory). This will give you access to the Wordpress functions. Note that you can also load wp-blog-header.php, it loads wp-load.php eventually; wp-load will be lighter weight in the end. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, wp insert post"
} |
Woocommerce: Making email clickable
So, here is my code in the order-detail.php file:
<li>
<span><?php _e( 'Email:', 'dokan' ); ?></span>
<?php echo esc_html( get_post_meta( $order->id, '_billing_email', true ) ); ?>
</li>
<li>
<span><?php _e( 'Phone:', 'dokan' ); ?></span>
<?php echo esc_html( get_post_meta( $order->id, '_billing_phone', true ) ); ?>
</li>
How would I make this clickable for both phone and email?
Thanks | This is really a vanilla PHP/HTML question, but for what it's worth:
<?php if ( $email = get_post_meta( $order->id, '_billing_email', true ) ) : ?>
<li>
<span><?php _e( 'Email:', 'dokan' ); ?></span>
<a href="mailto:<?php echo esc_attr( $email ) ?>"><?php echo esc_html( $email ) ?></a>
</li>
<?php endif ?>
<?php if ( $phone = get_post_meta( $order->id, '_billing_phone', true ) ) : ?>
<li>
<span><?php _e( 'Phone:', 'dokan' ) ?></span>
<a href="tel:<?php echo esc_attr( $phone ) ?>"><?php echo esc_html( $phone ) ?></a>
</li>
<?php endif ?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -2,
"tags": "woocommerce offtopic"
} |
Would it be wrong to save the permalinks as a postmeta and regenerate it on save post?
I was wondering about the permalinks. They are built on the fly but they are pretty much always the same. It seems like a waste of processing time and databse queries on every request.
Why not store them into the database and regenerate it when needed ?
What's wrong with that ? | Why waste storing (potentially) huge amounts of redundant, duplicate data, when you can store 1 pattern and only the unique "slug" for each post?
The processing power involved in generating permalinks "on the fly" is **so** insignificant in comparison to merely loading WordPress, it'd be like trying to make your car go faster by driving naked to save weight... | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "permalinks"
} |
Creating Structured Documents (books) in Wordpress?
I've been trying to rebuild one of my websites story archives in Drupal. I have a personal website I wouldn't mind putting in Wordpress, but I want an easy way to create structured documents. That is to say I wanr a parent Story page, that has links and hierarchy for the Chapters under it. Is this doable in Wordpress? | Try this plugin < Didnt use it myself but time ago I created something similar but using pages and then using a plugin to reorder them then you can create links in the sidebar to simulate an index.. very raw.. but works | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom field"
} |
Admin: Navigation Menus do not show empty categories/taxonomies in the list's search tab
**This is referring to the Admin area of Navigation menus**
It seems the normal behavior for building out Navigation Menus (Appearance>menus) is that when you expose categories or custom taxonomies, that list only shows terms that are not empty. This is fine behavior, but becomes a pain when trying to build out complex menus when the content is pending.
Does anyone know if there's a method or hook to tell Wordpress to allow empty categories to show up in these lists so they can be selected? Or is using custom links the only real option until content is entered?
_update:_ as noted below, they _do_ show up in the View All tab, but not when you do a Search. Additionally the view all tab is flat and not indented hierarchically.
This is probably an edge case so thanks for bearing with me! | In WordPress 4.1.1 at least, In the Menu editor, _Categories > View All_ Tab shows empty categories. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "categories, menus, admin, wp admin, taxonomy"
} |
Advantages/Disadvantages Using Theme Editor Instead of Pages
I'm working on a site and I prefer to create the site using the WordPress pages system. A co-collaborator assisting me with the site prefers to add pages using Theme Editor.
My first thought what is the advantage in doing this instead adding a new page via the dashboard?
Are there any disadvantages in creating pages using the theme editor?
If I wanted to use a plugin would the theme editor be able to use that plugin? Or does it isolate itself some how?
If anyone can shed some light on this that would be greatly appreciated. | You should understand that the theme editor is used to change the code structure of the pages something that cannot be achieved by simply creating a page via dashboard.
These are two very different things, while you can add html on your page using the page editor you cannot add some Php there. In simple terms theme editor allows you to edit the structure of pages, styling and create new page templates as well.
To use theme editor to make changes you need to have some Php knowledge or CSS for styling. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, pages"
} |
Shortcode not getting replaced
I used this to obtain my post:
$the_slug = 'kontakt';
$args=array(
'name' => $the_slug,
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 1,
'suppress_filters' => false
);
$my_posts = get_posts( $args );
The resulting post is:
!enter image description here
but the text still contains the plugins shortcode
`[wpgmza id="1"]`
I used the plugin
<
Am I using a way of parsing for the post that somehow stops the plugin from working?
Should I not use the text editor to add the shortcode? | Shortcodes get replaced when you output the content via `the_content()` function, or apply the filters hooked to `the_content`. If you look at raw post data, you will always see the original shortcode placeholder, that is normal and expected. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, shortcode"
} |
What's the purpose of 'taxonomies' parameter in register_post_type()?
As mentioned in `register_post_type()` Codex page:
> **taxonomies**
> ( _array_) ( _optional_ ) An array of registered taxonomies like `category` or `post_tag` that will be used with this post type. This can be used in lieu of calling `register_taxonomy_for_object_type()` directly. Custom taxonomies still need to be registered with `register_taxonomy()`.
> Default: no taxonomies
In my Custom Post Type (`product`) I'm also assigning two Custom Taxonomies with `register_taxonomy()` apart from the `register_post_type()`, and they are working fine. But there's a parameter in `register_post_type()` called `'taxonomies'` where it's said to mention all the taxonomies in an array, but even without this I'm achieving what it's meant to:
'taxonomies' => array( 'product_categories', 'product_tags' ),
So, I wonder what's the purpose of this? | To be really honest here, that is a useless parameter when used with custom taxonomies, as custom taxonomies are already registed to a custom post type when they are registered. Using the `taxonomies` parameter, you are re-registering a custom taxonomy to the custom post type
As stated by the codex, the `taxonomies` parameter is used to register build in taxonomies to custom post types, as build in taxonomies are registered to the build in post type `post`.
Just to close of, if you register a taxonomy to a post type, set the `taxonomies` parameter and use `register_taxonomy_for_object_type()`, you are doing the same job three times :-) | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "custom post types, custom taxonomy"
} |
Handle logo text color from admin section
Hi as per my requirement I need to have
> Color Picker option for Logo Text
see image !see the below image
> For **_TEXT2_** I need to have color picker option which can be managed from admin dashboard
I tried searching for plugins or custom code but not succeded is this possible if so please help me with procedure thanks in advance. | I ended up filling my requirement using this PLUGIN.It Does what I really needed. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "admin, color picker"
} |
Show post date on the page
What is the php code for showing post date on the page?
For example, it is a woocommerce product and here is the php code that I have so far:
does this work?
if ($hide_price !== '0') :
$output .= '<div class="mywoocmmerceprice>';
$output .= $product->get_categories();
//here is where I want to add the date
$output .= '</div>';
endif;
Thank you | `the_date()` is technically the template tag to do it. However it has a somewhat unusual aspect to only output once per date, so if there are multiple posts on page from same date they won't all show it.
`get_the_date()` is one level lower and retrieves (not outputs) a post's date without that bit of logic. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "date"
} |
Shortcodes Keep Wrapping in <p></p>
I've been ripping my hair out for hours and now I'm almost bald! :p Any time I try to insert any shortcode into the visual editor (on its own line), it wraps them in `<p></p>` tags. This happens when I save or switch to the text tab, even after I've manually removed the `<p></p>` tags. Wordpress is basically treating everything as text. It affects both default WP shortcodes and custom ones. Examples:
[gallery] -> <p>[gallery]</p>
[cardimg][/cardimg] -> <p>[cardimg][/cardimg]</p>
[W][/W] -> <p>[W][/W]</p>
I have tried every single solution here and on Google: < I don't know what to do at this point. Absolutely nothing I do changes the results. | Try <
It basically removes any `p`-tags before and after `[` or `]`, before rendering the content.
So the output of your shortcodes won't be wrapped in `p`-tags | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "shortcode"
} |
WPML customizing language selector
I want to show the language selector on my site but with the default include code "icl_language_selector" it shows the language full name. I only want to show the abbreviations of the language. For example ...
> English = ENG
> French = FR
Is this possible and how can I pull this off? | I dealt with this writing a custom template tag. You may want to adjust the structure and classes in order to fit the needs of your styling:
function mysite_languages() {
if ( function_exists( 'icl_get_languages' ) ) :
$languages = icl_get_languages( 'skip_missing=N&orderby=KEY&order=DIR&link_empty_to=str' );
if ( ! empty( $languages ) ) :
echo "\n<ul class=\"languages\">\n";
foreach ( $languages as $lang ) :
echo '<li class="' . ( $lang['active'] ? 'active' : '' ) . '"><a href=' . $lang['url'] . '>' . $lang['language_code'] . "</a></li>\n";
endforeach;
echo "</ul>\n";
endif; // ( ! empty( $languages ) )
endif; // ( function exists )
}
Further reference on WPML page: < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "multi language, plugin wpml"
} |
Single Must Use Plugins Directory for local development
I have multiple local installations of WordPress and want to have a single Must Use Plugins directory for all my local sites.
Is there anything I can add to wp-config for instance that will let me have a single folder which can be used for all my sites? Or perhaps another approach?
For instance:
/root/sites/site1/... /root/sites/site2/... /root/sites/site3/...
all use:
/root/mu-plugins/
Thanks | Yes, you can set the `WPMU_PLUGIN_DIR` constant in the config file of each of the sites (and `WPMU_PLUGIN_URL` for the url).
By default it is defined as:
WP_CONTENT_DIR . '/mu-plugins' | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugins, wp config"
} |
Category Page Custom Layout
I'm beginner in wordpress. I want to modify category page layout from this :
!Layout 1
into this :
!Layout 2
I'm using The7 theme.
I have read this Category Templates, but still don't know how to. I have create category-news.php from category.php in wp-includes folder. I want to know how to :
\- adding custom header in category page
\- change the content layout from grid (3 post) to list (4 post)
\- remove Leave a comment, Category Name and Author from under the title of the article/post and adding the text / post content (Contrary ... )
I'll modify pagination from CSS. | You should check out the options from this theme. Probably you can set all this in the theme options.
Accordion to the demo pages from The7 theme page you can choose for a list layout i.o a grid layout < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "pages, categories"
} |
Dropdown taxonomy lists in admin menu
I've added 4 taxonomy list to my wordpress backend:
1. BH Job Experience
2. BH Job Types
3. BH Job Regions
4. BH Job Tags
These taxonomy lists are added under **Job Listings** like this:
!enter image description here
Now I would like to have these 4 taxonomy lists under a dropdown with name **BullHorn**. Something like this:
!enter image description here
But I can't really find information about this. Can someone give me a tutorial, or a start, or some keywords I can search on? .. | Unfortunately WordPress does not support third-level admin menu, so there's no easy way to achieve the result you want.
You can only remove these 4 submenu items, add a submenu item instead which will be a link to a custom admin page and display these 4 links within that page (content).
Read about following hooks:
* remove_submenu_page()
* add_submenu_page() | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom taxonomy, themes, admin, taxonomy, admin menu"
} |
Should I find/replace values in the_content?
I'm creating a plugin specialized for a website. Most of the pages are pretty general (blog posts, contact pages, etc...) but a handful of pages will have custom code (specific SQL) for display statistics.
I'm wondering, best practices and what-not, is is better to build the page with all of the code inside of a function and then replace `the_content` using the filter... _OR_...should I build the html inside of the page (using the basic WP admin pages) and do a replace at certain spots for variable values?
Does this make sense? | Use shortcodes for that, that is exactly what they are for. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "the content"
} |
Translating publish dates to Arabic
I need to translate post publish dates from English to Arabic.
I uploaded the po file from this link, using WPML string translation: <
The .po file has translations for months, but not years and dates.
I want a date like 22 January 2015 to appear as ٢٢ يناير ٢٠١٥, but I can only get it to show up as 22 يناير 2015
What am I missing out? | Found it. Anyone with a similar problem can add this code to their site plugin or theme functions.php
function convert_numbers_to_arabic( $string ) {
$arabic_numbers = array('۰', '۱', '۲', '۳', '٤', '۵', '٦', '۷', '۸', '۹', '.');
$english_numbers = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.');
return str_replace($english_numbers, $arabic_numbers, $string);
}
add_filter( 'get_the_time', 'wpse_convert_arabic_time' );
add_filter( 'get_the_date', 'wpse_convert_arabic_time' );
function wpse_convert_arabic_time( $the_time ) {
if ( get_bloginfo( 'language' ) == 'ar' ) {
$the_time = convert_numbers_to_arabic( $the_time );
}
return $the_time;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "translation"
} |
At a Loss on over Page Peel Plugin Customization
I am trying to install and configure the Page Peel Plugin for a friend on their site. The plugin is from SmartRedFox.com and they're support is non-existent.
I have it installed but for some reason the Page Peel is not displaying. The code is present when I view Source but no image is visible. I've checked through the CSS and can't see the conflict.
Plugin installed here: < Should be visible in the Banner area which is marked by :
`<div id="PagePeel" class="right"></div>`
Granted I didn't develop this site so I am not sure why the original author has everything positioned absolute. | CSS was indeed the issue. It works fine on a stock WP installation and I was finally able to track down the conflict with this developed site. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, css"
} |
Stop WordPress from reserving slugs for media items?
I am experiencing some odd behavior, that apparently happens "out of the box" with WordPress.
If I upload a file through the media manager called: `services.jpg;` then go try to create a page with the permalink ` The slug `services-2` is given instead, because the attachment is already using that slug.
Visiting ` loads the attachment page.
I have not enabled any plugins or added anything into functions.php to modify the rewrites for attachments.
Has anyone run into this before? Know where to start to disable this functionality? | Thank you for the response everyone. I played around with macemmek's solution and I think it led me to an even better solution:
add_filter( 'wp_unique_post_slug_is_bad_attachment_slug', '__return_true' );
That is all that is needed. This will automatically 'skip' the default assigned slug on any attachment. So an attachment that might normally get the slug "services" will now get the slug "services-2". | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 6,
"tags": "permalinks, attachments, media, slug"
} |
custom user table columns
I'm doing this, which according to all of the documentation I've read, should override every column value in my manage users table. For some reason it's not working in WP 4.1. Any insight appreciated.
function retro_custom_users_table_content($value, $column_name, $user_id){
$value = "hi";
return $value;
}
add_filter('manage_users_custom_column','retro_custom_users_table_content', 10, 3); | The filter is only applied to custom columns that are added by you (or plugins and themes), not the default columns. If you want to modify the output of all default columns, I think you may have to add your own columns and duplicate the functionality of the defaults, then unset the defaults via `manage_users_columns`, since not all of them have filters to let you modify the values. When in doubt, dig into the source code and do a search for the filter to see it in context. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "columns"
} |
Mapping subdomain to point to sudirectory site in WordPress Multisite Network
I installed WordPress multisite (the sites runs in the root folder) and have created a site as a subdirectory. The web server used is Nginx.
I now want to map the main domain example.com to the parent site, and subdomain.example.com to the child site, which is installed in a subdirectory.
I tried using WordPress MU domain mapping, but I am not sure if it works for me. I am unable to test using my computer's hosts file.
The question is: Is it possible to get domain.example.com to point to mysite.com/subdirectory in a multisite network?
UPDATE: When I try to use WordPress MU domain mapping, and add an entry for the child site under Tools > Domain Mapping, I get a message 'New domain added'. But the new entry is not listed anywhere. What could be happening?
!enter image description here | I figured out what the problem was!
Whenever I went to Settings > Domain Mapping under the Network Admin panel, I always got a message: "Domain mapping database table created."
In fact, that database table was never created. The database user never had CREATE privileges.
Once I granted CREATE to the user, I was able to get subdomain.example.com to point to example.com/subdirectory. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "multisite, nginx"
} |
Filter for "get_post_type_archive_link()"
I tried to find filters or a hook to modify link returned by this function
`get_post_type_archive_link()`
I have gone through most of the documentation. I'm not sure it's not there or I'm not able to find it.
Any suggestions would be very appreciated. | The filter is `post_type_archive_link`, defined (WP 4.1.1) on line 1112 of file wp-includes/link-template.php:
apply_filters( 'post_type_archive_link', $link, $post_type );
And the use:
add_filter( 'post_type_archive_link', function( $link, $post_type ) {
//Do something
return $link;
}, 10, 2 ); | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 4,
"tags": "custom post types, filters, hooks, archives"
} |
Vimeo video embeds doesnt seem to work with ACF
I was trying to embed a vimeo link **into a site using ACF custom fields** and I am not getting anything in the front end but just a blank space as shown below.
!enter image description here
I tried multiple approaches including a vimeo iframe as well as just pasting the link but nothing seems to work.
The embed code is given below
<h3>Watch a Video</h3>
<iframe src="//player.vimeo.com/video/75791532?title=0&byline=0&portrait=0" width="500" height="375" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
I checked multiple sites and all of them say I should be able to embed using the iframe or just the link, so I am not sure whats happening here. | If the custom field contains just the URL you can achieve this using wp_oembed_get
$video_url = '
$video = wp_oembed_get( $video_url );
echo $video;
If the custom field contains other content as well something like this should work.
$content = '<p>Check out hte latest vid!</p>
$content = apply_filters('the_content', $content);
echo $content;
the_content filter automatically applies the oembed filter. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "embed, video player, vimeo"
} |
WP_User_Query orderby meta_val_num
I know that normal WP_Query's can have an `"orderby"` parameter of `"meta_value_num"`, but when I try to user `"orderby" => "meta_value_num"` on a WP_User_Query, it doesn't seem to work. Anyway I can obtain this functionality or is there something I'm missing?
Edit:
Here's what I've tried to retrieve results ordered by numeric meta values:
$sorted_users = new WP_User_Query(array(
'orderby' => 'meta_value',
'meta_key' => 'satisfaction_rating',
'order' => $order,
'role' => 'subscriber',
'meta_query' => array(
array(
'key' => 'satisfaction_rating',
'type' => 'NUMERIC'
)
)
));
Still doesn't seem to work... | This is untested, but I believe if you set `type` in your meta query to `numeric`, that will cast the values as numbers so orderby `meta_value` should work correctly. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query, query, order, wp user query"
} |
Change the permalinks structure
I have decided my structure of permalinks from /?p=125 to /sample-page. I have tried some methods, but anyone works. I have changed the structure in settings/permalinks and I have tried with some plugin in order to get a redirecction, however I have not get anything. I don`t know what to do, because I get 404 error when I open any of my pages. I would like to know how to solve this problem, and if it has any relation with my server. | When you save permalink settings, is there the following notification at the bottom of page?
> If your .htaccess file were writable, we could do this automatically, but it isn’t so these are the mod_rewrite rules you should have in your .htaccess file. Click in the field and press CTRL + a to select all.
I'm asking because the behaviour you described may be caused by non-existing or non-writable .htaccess file in your WordPress root.
If you have a shell access to the server environment (or you work locally), you can create this file and add writing permissions:
cd your_wp_directory
touch .htaccess
chmod a+w .htaccess
After that, save permalink settings again. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "permalinks, pages, 404 error"
} |
How to add a css class to custom field value?
In the user's profile there is a dropdown list with options to choose from. The custom field name is colors with several values: red, green, blue, etc. Can I add a css class to those values. Like red_css, blue_css etc? To style accordinly. .blue_css {font-size: 10px;}
Is that even possible? Thanks | It's very similar to how you set / access theme options:
<
setting:
`update_user_option( $user_id, $option_name, $newvalue, $global )` <\- taken from wordpress codex.
and getting :
<
`get_user_option('color_option', $userID);`
To get your specific request fulfilled, you would need to find the user_option(s) and then append to the list via a plugin or theme customization | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom field, css"
} |
Limit loop to future events
I have a custom post type, `basic_events`, with a custom date field, `date_of_event`. My view shows these posts in ascending order, based on this custom date field.
$args = array(
'post_type' => array('basic_events'),
'order' => 'ASC',
'orderby' => 'meta_value_num',
'meta_key' => 'date_of_event',
'paged' => $paged
);
Since everything is sorted by that field, and not by post type or an internal WordPress date, I'm having a hard time figuring out how to limit this view to only show FUTURE events.
What is the best way to limit to view to future events? | Assuming your date is in the correct format for proper ordering (yyyy-mm-dd), add a `meta_query` to your args:
$args = array(
'post_type' => array('basic_events'),
'order' => 'ASC',
'orderby' => 'meta_value_num',
'meta_key' => 'date_of_event',
'paged' => $paged,
'meta_query' => array(
array(
'key' => 'date_of_event',
'value' => date( 'Y-m-d', current_time( 'timestamp' ) ),
'compare' => '>',
'type' => 'DATE'
)
)
);
**EDIT** \- Changed `date( 'Y-m-d' )` to `date( 'Y-m-d', current_time( 'timestamp' ) )` to get the date relative to your site's timezone settings. See `current_time` in Codex for info. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query, date"
} |
Changing a setting in the wp-admin/customize.php reverts CSS styles to parent theme
I have a child theme built ontop of the Cherry Framework theme.
Whenever an admin user goes to wp-admin/customize.php and changes the slider, the CSS gets completely destroyed and needs to be backed up.
Has anyone had any experience with the Cherry framework and why it could be causing this?
**What would I need to add (or remove) to the functions.php to completely disable the customize page to prevent the end user from accidentally causing this problem in the future if they poke around?**
edit:
<
Seems like a common issue with the Cherry framework, anyone seen any solutions?
Can this really be off-topic for the WordPress site? It's about WordPress theming. It's directly related to WordPress development, and not general PHP development. | The changes were being made in a stylesheet that is auto-generated by the parent theme. In the specific case of the Cherry parent theme (which is widely used in templates sold on themeforest, templatemonster etc), you cannot make stylesheet changes in reserved files such as main-styles.css (Despite them existing in a child theme).
The solution is to either make style changes in the style.css, or to make a stylesheet with a dependancy on main-styles.css, in order to override any auto-generated styles.
I.e.
<?php wp_enqueue_style( $handle, $src, 'main-styles', $ver, $media ); ?>
Can read more about the solution here:
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "customization, wp admin, child theme"
} |
WordPress Pages “allow comments” meta option can't be checked
I'm trying to allow comments on WordPress pages, but when I check the page's "Allow Comments" meta checkbox option ( ) and save page, it does NOT save settings, it returns to an UNCHECKED box again! Don't know why?!
My default discussion settings as the following:
PS: it works well on POSTS, but PAGES does not!
Any ideas about how to fix that?
Thanks in advance! | Thanks to the theme developers for helping me fixing it.
I'm posting the answer here in hope that it may helpes any person facing the same problem.
In **functions.php** there was a code to disable comments on **page.php**
Remove this part of code from **functions.php** to make the comments working on pages too:
function default_comments_off( $data ) {
if( $data['post_type'] == 'page') {
$data['comment_status'] = 0;
}
return $data;
}
add_filter( 'wp_insert_post_data', 'default_comments_off' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "pages, comments"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.