INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How to center a video
I can not center a video in a wordpress blog post. Here is the shortcode used for the video:
[video width="1920" height="1080" m4v="
It is an mp4 video file from my uploaded media. I have tried to add this to my style.css, and still did not work:
.wp-video {
text-align: center;
margin-left: auto;
margin-right: auto;
}
Any help please.... | To center an element, you will also have to style it's parent element too. So let's say, you video has a structure like this:
<div class="parent-class">
<video class="wp-video">
</video>
</div>
To center the video, you will have to give it's parent a width. Using:
.parent-class{
width:100%;
display:block;
}
Now, you can use this to do the final touch:
.wp-video {
text-align: center;
margin: 0 auto;
max-width: 400px;
display: block
}
Notice that you have to define a width for this video, since your video has a width of 1920px, which for sure will overflow most of the screens. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "css, embed"
} |
Exclude parent with child pages from WP_Query
How can I query only those pages that **DO NOT HAVE** child pages?
E.g.:
* Parent page 1
* Child page 1
* Child page 2
* Parent page 2
* Parent page 3
* Child page 1
* Child page 2
* Parent page 4
I would like to show
* Parent page 2
* Parent page 4
$newQuery = new WP_Query( array (
'posts_per_page' => -1,
'post_type' => 'page',
// Solution?
) );
`
Thanks | the_dramatist's answer will give you only top-level pages that have no children, which matches the example given in your description.
However, if you want to get ALL leaf pages, use the following:
SELECT *
FROM $wpdb->posts
WHERE
post_type = 'page' AND ID NOT in
(
SELECT ID
FROM $wpdb->posts
WHERE
post_type = 'page' AND ID in
(
SELECT post_parent
FROM $wpdb->posts
WHERE post_type = 'page'
)
) AND post_status = 'publish' | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query, pages, child pages"
} |
How to run word press theme on localhost in Ubuntu OS?
I am new for wordpress and i am using Ubuntu OS on my computer I want to run a downloded theme on localhost how can i do that? | Here is two method for downloaded theme.
1. Then login as admin and navigate **Dashboard >> Appearance >> Themes**. Then click on Add new button then click on Upload theme button and browse download theme zip file like theme.zip. and click on install button. After installing theme click on activate theme button.
**Note :** Your wordpress folder have **read/write** permission.
2. Paste your downloaded theme into **themes** directory located at **your_wordpress_folder/wp-content/** directory. Then login as admin and navigate **Dashboard >> Appearance >> Themes** and active your downloaded theme.
View How To Install A Theme On Localhost tutorial for more guidance. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "themes"
} |
Wordpress categories being called "archives" in google links. How to remove?
We have several category pages. When you find these links on google we noticed that google is adding the name "Archive" to all our category pages.
How do i change this? I would like to remove the reference all together.
Thanks for any help!!\[enter image description here]1 | This is likely that you are using an SEO tool. Go to the settings for that tool and remove the word "archive" from the archive section of your SEO. If you DON'T have SEO tool, then get one. An example would be Yoast (this is by no means a recommendation, just an example) and in it's settings you'll be able to remove the "archive" from archive titles. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "categories, archives, google"
} |
Search custom taxonomy term by name
I have a custom taxonomy, called albums.
I need to be able to text search the taxonomy term title, obviously this isn't default WP Search. Just wondering how I'd best tackle this?
Say there is an album called 'Football Hits',
I start typing foot and search that, all I need it to appear is the album title and the permalink.
Thanks! | // We get a list taxonomies on the search box
function get_tax_by_search($search_text){
$args = array(
'taxonomy' => array( 'my_tax' ), // taxonomy name
'orderby' => 'id',
'order' => 'ASC',
'hide_empty' => true,
'fields' => 'all',
'name__like' => $search_text
);
$terms = get_terms( $args );
$count = count($terms);
if($count > 0){
echo "<ul>";
foreach ($terms as $term) {
echo "<li><a href='".get_term_link( $term )."'>".$term->name."</a></li>";
}
echo "</ul>";
}
}
// sample
get_tax_by_search('Foo'); | stackexchange-wordpress | {
"answer_score": 12,
"question_score": 5,
"tags": "wp query, permalinks, taxonomy, search"
} |
Fix Problem With Textdomain Translation
I translate some text with textdomain:
_e( 'My Text', 'my-text-domain' );
And I am using Loco Translate plugin. It was working fine, but now it has stopped working.
What is the best way to find the problem why it`s not working? | Check that the file style.css is written:
Text Domain: my-text-domain
Check that is activated in the template files:
load_theme_textdomain('my-text-domain'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "translation, textdomain"
} |
JavaScript in WordPress Customizer
Customizer Codes:
$wp_customize->add_setting (
'script-code',
array (
'default' => esc_html__( 'Script Code', 'x' ),
'sanitize_callback' => 'wp_kses_post'
)
);
$wp_customize->add_control (
new WP_Customize_Control (
$wp_customize,
'script-code',
array (
'label' => esc_html__( 'Script Code', 'x' ),
'section' => 'script',
'settings' => 'script-code',
'type' => 'textarea',
'priority' => 1
)
)
);
Photo from Customizer:
); ?>
from output, return the empty:
<main class="script-code">
</main>
How can I use script tag in Customizer textarea setting field ?
Thanks so much. | This is because you are using wp_kses_post to sanitize the output data, try without it:
<?php echo get_theme_mod( 'script-code'); ?>
also remove it from here:
$wp_customize->add_setting (
'script-code',
array (
'default' => esc_html__( 'Script Code', 'x' ),
'sanitize_callback' => '' // remove wp_kses_post
)
);
also make sure you are using the right name of your theme mod you can check that in two ways:
1.- do a `var_dump(get_theme_mods());` check there how is named.
2.- Inspect the `HTML` code of your control in the customizer
 ) {
// User has assigned menu to this location;
// output it
wp_nav_menu( array(
'theme_location' => 'topheader',
'menu_class' => 'topMenu', /* bootstrap ul */
'walker' => new My_Walker_Nav_Menu(), /* changes to a bootstrap class */
'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>',
'menu_id' => 'topMenu'
) );
}
If there are no links in the menu, nothing shows in the front-end. Is it possible to display a link to add a menu? Which takes the user to the menu location in dashboard. | Its possible:
if (has_nav_menu('topheader')) {
// User has assigned menu to this location;
// output it
wp_nav_menu(array(
'theme_location' => 'topheader',
'menu_class' => 'topMenu', /* bootstrap ul */
'walker' => new My_Walker_Nav_Menu(), /* changes to a bootstrap class */
'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>',
'menu_id' => 'topMenu'
));
}else{
if (is_user_logged_in()) { //we check if the user is logged in
echo '<a href="/wp-admin/nav-menus.php?action=edit&menu=0">Add New Menu</a>';
}
}
this will open the menu dashboard ready to create a new menu. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "menus"
} |
Query/list all terms and their custom post count
I want to query/list all the terms (from all the custom taxonomies) within a custom post type with their custom post count. This is what I have so far...
$the_query = new WP_Query( array(
'post_type' => 'teacher',
'tax_query' => array(
array(
'taxonomy' => 'ALL CUSTOM TAXONOMIES',
'field' => 'id',
'terms' => 'ALL TERMS'
)
)
) );
$count = $the_query->found_posts;
$term_name = $the_query->get_term;
echo $term_name;
echo ' - ';
echo $count; | If the taxonomies in question are used ONLY in the post_type in question, then the following simple function will do what you need:
function
count_term_use ($post_type)
{
$args = array (
'taxonomy' => get_object_taxonomies ($post_type, 'names'),
) ;
foreach (get_terms ($args) as $term) {
echo "$term->name - $term->count\n" ;
}
return ;
}
However, if a taxonomy is shared by multiple post_type's then the above counts will reflect the total number of posts of any type that use the term, which is not what you're looking for. If that is true in your case, let me know and I'll post the more complicated (and expensive in terms of execution time/db queries) code. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, wp query, custom taxonomy, query posts, count"
} |
Is it possible to prevent website from breaking with auto update?
Recently i've noticed a lot of posts from users, complaining about their website running into problem after updating the WordPress to the latest version.
Let's say i have a website with a lot of custom functions and codes, which depends on the current core to run. The functions are too many to watch, maybe 30 or more, and WordPress is releasing update every once in a while.
So, how can i leave the auto update to ON and be sure that this feature won't break my Blog? I know i can make backups regularly, but this is not an actual salvation.
The path notes may be helpful, but still, on custom templates it's a pain to check it every time an update is release.
Now what are my choices? Do i have to turn the auto update OFF and backup / update manually? Or is there a way / plugin / etc. to prevent such things from happening? | A website is just like any other software product, any change need to go through QA stage first, no matter how trivial it might seem. This is why you should always test all updates on a staging/dev server before pushing it to production.
As always it comes down to a question of ROI. Simple blogs can suffer down time for days while a fix is being work on, while sites that generate 1000$/hour probably less tolerant to hiccups, and the time invested in proper QA to avoid it is totally worth it.
So it is your judgment call in the end of how bad will it be for you if an update will break you site. If you value your time in lets say 40$/hr and the site generates 5$/hr, it is just not worth it for you to have a 3 hours QA cycle on the bi-monthly update release (not official but this is the real life rate), especially if you don't have any bad hacks in your code and it should in theory be "future prof" | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "automatic updates"
} |
How to translate theme content using site language?
I have theme. For example code for comments:
<?php
'fields' => array(
'author' => '<p class="comment-form-author">' . '<label for="author">' . esc_html__( 'Name','text_domain' ) . ( $req ? ' <span class="required">*</span>' : '' ) . '</label> ' .
'<input id="author" name="author" type="text" value="' . esc_attr( $commenter['comment_author'] ) . '" size="30"' . $aria_req . ' placeholder="'.esc_html__( 'Name','text_domain' ) .'"/></p>',
)
...
);
?>
I have changed site language in admin panel, but i still get 'Name' (english). How to translate theme content using site language? | Make sure to load the translations using the **load_theme_textdomain** function, and supposed your translations is located in the **library/translations** folder, then you can add the code below in you **functions.php** file.
// let's get this party started
add_action( 'after_setup_theme', 'translations');
function translations() {
// let's get language support going, if you need it
load_theme_textdomain( 'text_domain', get_template_directory() . '/library/translations' );
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "localization"
} |
How to delete a theme using AJAX
I want to delete a theme using an AJAX request.
I've looked through the `ajax-actions.php` file and saw this: `wp_ajax_delete_theme()`, but how do I trigger it?
I want to add this 'delete theme' function to my WordPress plugin.
If anyone can explain this to me, it's very much appriciated. | You can do this by creating a post form with a nonce field...
$url = admin_url('admin-ajax.php');
echo '<form action="'.$url.'" method='post'>';
echo '<input type="hidden" name="action" value="delete_theme">';
wp_nonce_field('updates'); // to pass check_admin_referer
echo '<input type="hidden" name="slug" value="twentythirteen">';
echo '<input type="submit" value="Delete TwentyThirteen Theme">';
echo '</form>';
You can replace the hard-coded `slug` input field with a `<select>` one and loop through installed themes to add them as the select options if you like, but I've given it this way because you say you want to delete _a_ theme. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, php"
} |
Remove current_page_parent from posts page link in WordPress nav menu
I have set a page to be the posts page. So when I visit single posts the link for posts page in nav menu has a class 'current_page_parent'.
But when I visit single posts for a custom post type, then also it is adding 'current_page_parent' to the link for posts page.
How can I restrict it and not add the class when I visit single custom post types page. | I assuming you're using wp_page_menu() or wp_list_pages(). If so, then what you need to do is hook into the page_css_class filter, e.g.,
add_filter ('page_css_class', 'my_func', 10, 5) ;
function
my_func ($classes, $page, $depth, $args, $current_page_id)
{
if (/* test condition */) {
$classes = array_diff ($classes, array ('current_page_parent')) ;
}
return ($classses) ;
}
where `/* test condition */` is where you'd put your logic to decide when that class should be included. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "custom post types, menus"
} |
wp_set_object_terms not accepting variable array
I am trying to use the following command:
wp_set_object_terms( $myID, $myissuearray, 'my_issues', true );
But for some reason, it won't accept my variable array.
That array, `$myissuearray`, using `error_log(print_r($myissuearray,true))` outputs:
Array
(
[0] => 9
[1] => 10
[2] => 77
[3] => 12
)
Which sure looks like a valid array to me.
If on the other hand, I don't use my variable and set the issue array by hand in the command to something like:
wp_set_object_terms( $myID, array(9,10,77,12), 'my_issues', true );
the command works and the terms are set. I am stumped as to what I am doing wrong. Why won't this command accept my variable array?? | Ok, so it turned out that my array was an array of strings somehow, which using var_dump (instead of print_r) revealed. Then I needed to convert my array to int values, which I did thus:
$myissuearrayINT = array_map('intval', $myissuearray);
And now, when I do the following it works as expected:
wp_set_object_terms( $myID, $myissuearrayINT, 'my_issues', true );
Hope this helps someone else out there... | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "array, terms"
} |
How do I get the name of a menu in WordPress?
I'm currently setting up a sidebar menu with multiple menus and sections. Each section with the title (the menu name) and a bunch of links underneath (the menu items) - I printed the items, but how do I print the menu name?
Thanks,
Jacob | You can access the menu metadata using the `wp_get_nav_menu_object` function
BY NAME:
$menu = wp_get_nav_menu_object("my mainmenu" );
BY SLUG:
$menu = wp_get_nav_menu_object("my-mainmenu" );
The return object as follows:
Object (
term_id => 4
name => My Menu Name
slug => my-menu-name
term_group => 0
term_taxonomy_id => 4
taxonomy => nav_menu
description =>
parent => 0
count => 6
)
To display the name:
echo $menu->name; | stackexchange-wordpress | {
"answer_score": 13,
"question_score": 10,
"tags": "menus"
} |
Get posts from Network (Multisite)
The following code gives all posts from the network. What I am trying to achieve :
* Select which blogs to display (by ID)
* Select how many post to display (My code selects how many post **per blog** )
* Order by date or random
$blogs = get_last_updated();
foreach ($blogs AS $blog) {
switch_to_blog($blog["blog_id"]);
$lastposts = get_posts('numberposts=3');
foreach($lastposts as $post) : ?>
<a href="<?php echo get_permalink(); ?>"><?php the_title(); ?></a></h3>
<?php endforeach;
restore_current_blog();
} | I created a plugin which does something similar (called Multisite Post Display < ) . It displays posts from all multisite sub-sites.
The code in there might be helpful for what you are doing. You are welcome to dig into it and use the code to help with your project. (After all, I used other people's code snippets to develop it.)
I wrote it after I did the Multisite Media Display, since I wanted a way to display media from subsites on one page, and couldn't find any plugin that did that. Both have been useful to monitor posted media and content from my multisite.
Free, open source, and all that. Hope it is helpful. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 7,
"tags": "wp query, multisite, get posts"
} |
Can Transients be used to store sensitive data?
Can I use WordPress Transients to store 'sensitive' data? For example login tokens or Captcha answers?
As far as I know all themes and plugins have access to transients. What would be another good way to store this kind of details?
Edit: The reason I ask this question is that I am creating a 2 Factor Authentication plugin that generates a login token. This token is sent via SMS or e-mail to the user. What would be a safe way to store this token. | Yes you can, transients is on your server, not accessible by front end client. You can use also update_option() < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "transient"
} |
Set cookie using GET variable
I need to set a cookie based on a GET variable so my customers can get a coupon code on our site even if they move around after selecting the coupon link.
I am using the code here: Gravity Help to populate the coupon field based on the cookie. Just the second half of the code.
I need to set the coupon code in a cookie. There is a piece here: Setting a Cookie using a variable from the URL But I think that will also set an empty cookie if there is no variable which I think would over write the code if they user browses around the site. What would be the best way to make sure that function only runs if the variable is set? | Just check if the variable is set, using the code from your link:
add_action( 'init', 'set_agent_cookie' );
function set_agent_cookie() {
if (isset($_GET['code'])) {
$name = 'agent';
$id = $_GET['code'];
setcookie( $name, $id, time() + 3600, "/", COOKIE_DOMAIN );
}
} | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 5,
"tags": "variables, cookies, plugin gravity forms"
} |
Custom WP Comments Query with Nested Comments Possible? (Hierarchy/Depth)
I've set up a custom WP Comments Query that serves approved comments on posts ordered by date (basic stuff) and everything works fine except the fact that comments are displayed below each other and I'd like them to be nested — like if I was using `wp_list_comments()`.
Is there any template file/function to output comment template to the query so the comment will have a basic wp comment html structure with all the wp classes and reply links?
The reason why I can't use the `wp_list_comments()` is that it doesn't allow to set the `post_id` which I need to set as I'm fetching posts via AJAX, and this function doesn't work properly outside the loop...
Any help/idea is very welcome, thanks a bunch! | you can pass an array of WP_Comment objects into `wp_list_comments` as second argument.
// Query
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $args );
// Display
wp_list_comments(array(), $comments); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "comments"
} |
WordPress Import shows an error when uploading previously exported xml file
First time I faced this problem & trying to find out solution but it seems to me that it happens very few and that is why no more solution has been found like this & that is why I am here.
WordPress Import Message:
> File is empty. Please upload something more substantial. This error could also be caused by uploads being disabled in your `php.ini` or by `post_max_size` being defined as smaller than `upload_max_filesize` in `php.ini`.
I am getting above message when trying to import a previously imported file like the bellow image. Could you please tell me how to solve this?
 . '/wp-content/temp/');
via ftp in the folder `/wp-content`, create a new catalog `/temp/` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 3,
"tags": "images, uploads"
} |
How do I remove the WordPress version from the browser source?
I want to remove the WordPress version from my Source Code. To achieve this, I have placed the following code in my functions.php file:
function wordpress_remove_version() {
return '';
}
add_filter('the_generator', 'wordpress_remove_version');
This code has worked for me in the past but for some reason, the WordPress version is still appearing in my Source Code.
I have deactivated my Plugins but still with no success. Nor has trailing the internet for any updates on new codes etc.
Has anyone else got this problem or know of where may be going wrong? | I have figured out the problem!
For anyone reading this, my code does work perfectly fine. The issue lied within my functions.php file.
Rather than have the following in my file:
function theme_name_script_enqueue() {
wp_enqueue_style( 'wpb-fa', get_template_directory_uri() . '/fonts/css/font-awesome.min.css', array(), '1.0', true );
}
add_action( 'wp_enqueue_scripts', 'theme_name_script_enqueue' );
I had ...
function theme_name_script_enqueue() {
wp_enqueue_style( 'wpb-fa', get_template_directory_uri() . '/fonts/css/font-awesome.min.css' );
}
add_action( 'wp_enqueue_scripts', 'theme_name_script_enqueue' );
Note that I was missing `, array(), '1.0', true`
Once the above was inserted, all worked perfectly fine. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wordpress version"
} |
How to remove row action "Edit with Visual Composer" in the post list table?
* I am using Visual Composer plugin.
* I've found a snippet to remove row actions in post list table in word press.
add_filter( 'post_row_actions', 'remove_row_actions', 10, 1 );
function remove_row_actions( $actions )
{
if( get_post_type() === 'my_cpt' )
unset( $actions['view'] );
return $actions;
}
* but I could not found the row action name for the `Edit with Visual Composer`
* I want to remove or edit the link into the Row Action "".
Have a look on screenshot
;
on your test install to find the key or search the plugin code for `page_row_actions`.
In some cases one should be able to remove the `page_row_actions` filter callback with `remove_filter()`, but some plugins make it harder.
ps: I think you're looking for the `edit_vc` row action key. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, row actions"
} |
Code to create a redirection after login?
I get this code to create a redirection after login. I see no error but it doesn't work. No errors, it just do nothing at all.
I added this code to functions.php in my child theme.
/*******************************
REDIRECTION
*********************************/
add_action('wp_head','redirect_admin');
function redirect_admin(){
if(is_admin()&&!current_user_can('level_10')){
wp_redirect(WP_HOME.'/quote-list/');
die; // You have to die here
}
} | You can use the `login_redirect` hook.
function redirect_admin( $redirect_to, $request, $user ){
//is there a user to check?
if ( isset( $user->roles ) && is_array( $user->roles ) ) {
//check for admins
if ( in_array( 'administrator', $user->roles ) ) {
$redirect_to = WP_HOME.'/quote-list/'; // Your redirect URL
}
}
return $redirect_to;
}
add_filter( 'login_redirect', 'redirect_admin', 10, 3 );
Example taken from WordPress Codex
Also is_admin() does not check if the user is an administrator but if the administration panel is being displayed. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "redirect, wp redirect"
} |
Conditional Site Logo(Category Based)
I'm trying to setup a multi-topic blog.
My topics are:
1. Food
2. Lifestyle
3. Fiction
4. Digital Reality
I have 4 different logos for each category and want to display them depending on the category of the article.
The URL slug will have the category mentioned in it. Please help me display logo depending on the category.
Would be amazing if this can be done by editing the child theme.
Thank you. | You could check the current category and apply a different class with each logo,
$cur_topic = $queried_object->slug;
$my_class = 'default-logo';
switch ($cur_topic) {
case "food":
$my_class = 'food-logo';
break;
case "lifestyle":
$my_class = 'lifestyle-logo';
break;
case "fiction":
$my_class = 'fiction-logo';
break;
default:
$my_class = 'default-logo';
}
echo '<div class="' . $my_class . '"></div>';
**Alternatively** , check out the following plugin:
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, custom header, logo"
} |
Pulling Data from CSV vs. pulling data from database
I developed a custom post type with a custom taxonomy for my WP theme and I need to add a number to associate with my taxonomy.
Example: The taxonomy is "store" and the average savings for that store is "20".
I created an interface to add average savings while creating and editing the taxonomy. The number is stored in wp_options table for the particular taxonomy ID. On the other hand, my colleague created added a CSV file in the root directory and wrote a function to open the file and fetch the number according to the taxonomy name, every time a taxonomy page is loaded.
I just need to know which is the best method to do this and why? | Reading, searching and closing a file every time the page is loaded is highly time consuming. Database systems are highly optimized for reading and writing huge amount of records, querying data, providing schemes, relations between the data etc.
What will happen if 10K users hit the taxonomy page? How you will handle the updates of a taxonomy or the insertion of a new one in the file? How you can do efficiently queries regarding the value saved in the CSV file? What will happen if you delete the taxonomy or if the file has 1 million records?
**The proper way is to save it in a database.**
You can read more here and here | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "taxonomy, options, csv"
} |
What's the algorithm to verify user password?
I've the need to export user and hashed password from tbl_user to a new custom developed CMS.
> I'm not here to ask how to reverse the password !
I'd like only to know the steps, given a plain password, to create the SAME IDENTICAL password used by wordpress (4.7)
Is this possible? Is the algorithm available? | First: Be aware that this is pluggable in WP so first of all check that you're site is using the default implementation.
Then have a look at `wp_hash_password` and `wp_check_password` in `pluggable.php` and the `PasswordHash` class. There you should find what you are looking for. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "password"
} |
Page Revision date displaying on google search
This must likely is a noob question, but I'm trying to remove the revision date that is showing up on my pages on a google search.
I'm unable to find a answer to this on google, as all answers are regarding posts not page. Any help would be appreciated

<
Waiting for an effective solution :)
Thanks in advance | The following should do the trick:
global $wpdb ;
// get the post_ids from the custom table
$sql = "SELECT listing_id FROM {$wpdb->prefix}wpdbdp_listing_fees WHERE fee_id = %d" ;
$sql = $wpdb->prepare ($sql, 4) ;
$post_ids = $wpdb->get_col ($sql) ;
// get the custom posts from the posts table
$args = array (
'post__in' => $post_ids,
'post_type' => 'wpbdp_listing',
) ;
$posts = new WP_Query ($args) ;
foreach ($posts->posts as $the_post)
echo $the_post->post_title ;
}
Note the use of `$wpdb->prefix` in the SQL statement. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, wp query, database, mysql, conditional content"
} |
How to display author above content-single.php post
I am using a modified version of the Twenty Sixteen wordpress theme and I would like to have the author display at the top of the post.
Currently I have the author username being posted but this isn't what I want
Here is how I did it
<?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
<?php $username = get_userdata( $post->post_author ); ?>
<p style="display:inline-block;">Author: </p> <a href="<?php echo get_author_posts_url( $post->post_author ); ?>"><?php echo $username->user_nicename; ?></a>
<?php the_date('m-d-Y', '<p>', '</p>'); ?>
<br />
But like I said this displays 'Author : (username)' which is not what I want. I want their author name to display.
I know that I'm close. But when I try to replace the username portion nothing displays. So I must be doing that wrong. | Use `the_author();` you can read more about it here. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php"
} |
What might be removing my redirects from my htaccess?
My rewrite rules and redirects are somehow being removed from my htaccess file. The iThemes Security plugin developer says iThemes doesn't remove anything from htaccess, so my question is what does? What could the culprit be?
(If it matters, my Wordpress install is in a subdirectory, but I'm referring here to the root htaccess.) | Whatever's inside the "# BEGIN WordPress" and "# END WordPress" lines in your .htaccess file will be re-written by WordPress every time the permalinks are updated...
I assume your plugins also use a similar mechanism.
So make sure your _own_ rewrites are always outside other people's blocks. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "htaccess"
} |
get_post_meta remains empty while looping all menu items and using the ID
I am trying to create some sort of custom menu. Where I list all titles of my pages in the main menu and display the value of a meta box of each of these pages. For some reason the get_post_meta remains empty for all items. I fail to see why.
<?php
$array_menu = wp_get_nav_menu_items('header-menu');
$menu = array();
foreach ($array_menu as $m) {
if (empty($m->menu_item_parent)) {
?>
<h4><a href="<?php echo $m->url;?>"><?php echo $m->title;?></a></h4>
<p>
<?php echo get_post_meta($m->ID, 'meta_box_subtitle', true); ?>
</p>
<?php
}
}
?> | You are sending the `ID` of the menu item not the `ID` of the page try using `url_to_postid()` like this:
<?php
$array_menu = wp_get_nav_menu_items('header-menu');
$menu = array();
foreach ($array_menu as $m) {
if (empty($m->menu_item_parent)) {
?>
<h4><a href="<?php echo $m->url;?>"><?php echo $m->title;?></a></h4>
<p>
<?php global $wp_query;
$pageID = url_to_postid( $m->url );
echo get_post_meta($pageID, 'meta_box_subtitle', true);
?>
</p>
<?php
}
}
?> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "post meta"
} |
What happened to the WordPress dashboard?
I installed MAMP on my system, installed WordPress, installed a theme and customized it and everything worked great. However, when I started MAMP today it does not take me to the WordPress dashboard, but rather directly to the website itself.
If someone can help me resolve this so I can gain access back to my dashboard, it would be very much appreciated.
Thanks | Navigate to <
If you are still getting redirected to the main site check your database, MAMP I beleive comes with PHPmyAdmin, login to that and check your SITE_URL in the WP_OPTIONS table and then check the WP_USERS table to see if your user account is still registered as an admin. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "dashboard"
} |
MathJax inside shortcode
In my custom theme I included some shortcodes. One of them is called `[alert]...[/alert]` and results in a bootstrap alert box. It accepts a type (warning, danger, info or success), a title and the main content. The output is a simple return:
return '<div class="alert alert-' . $atts['type'] . '" role="alert"><p class="alert-title">' . $atts['title'] . '</p>' . $content . '</div>';
I need to wrap an important math formula by one of these alerts, so I wrote:
[alert type="warning" title="Important Formula"][latex]a^2 + b^2 = c^2[/latex][/alert]
But this outputs:
<div class="alert alert-warning" role="alert"><p class="alert-title">Important Formula</p>[latex]a^2 + b^2 = c^2[/latex]</div>
So the mathjax latex shortcode is not being recognized and thus is not translated into a mathematical formula. Outside the alert shortcode they are translated into a formula.
Does anybody know what's happening here? | You cant call a shortcode inside a shortcode they do not automatically nest, you need to use `do_shortcode($content)` like this (i am assuming the name of your shortcode):
function alert_shortcode( $atts, $content = null ) {
return '<div class="alert alert-' . $atts['type'] . '" role="alert"><p class="alert-title">' . $atts['title'] . '</p>' . do_shortcode($content) . '</div>';
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "shortcode, plugin mathjax"
} |
Add menu option to "New Post" menu in admin bar
I'm trying to figure out how to add an item to the new menu bar. To be clear, I know how to add items to the menu bar. I want to add something new under the bug plus sign in the admin bar. Here's a pic of the admin bar I'm looking to add an item to.

'title' => 'test', // alter the title of existing node
'parent' => 'new-link', // set parent to false to make it a top level (parent) node
'href' => admin_url('admin.php?page=enter_timesheet')
);
$wp_admin_bar->add_node( $args );
I'm assuming I just need to modify the 'parent' tag to something, but I'm not sure what. I've found this to be shockingly poorly documented (or my Bingle-foo is failing me). | Use `new-content` :
function make_parent_node($wp_admin_bar) {
$args = array(
'id' => 'test1234', // id of the existing child node (New > Post)
'title' => 'test', // alter the title of existing node
'parent' => 'new-content', // set parent to false to make it a top level (parent) node
'href' => admin_url('admin.php?page=enter_timesheet')
);
$wp_admin_bar->add_node($args);
}
it will show at the bottom:

Is it possible to set a newline character `\n` as a URL entity when using `esc_url()`? The URL entity for a newline is `%0A` as mentioned here: <
But `esc_url()` strips out the `%0A`.
Any help appreciated. | # Background:
WordPress strips out `%0A` from URL because in general newline has no practical purpose in URL. Unless it's a `mailto:` protocol, WordPress strips out `%0A`.
So it's better not to use them in URL at all.
# Solution:
Still, if for any specific purpose you have to use `%0A`, you may use `%250A` and then filter it back to `%0A` using `clean_url` filter.
> `%250A` is URL encoded version of `%0A`, i.e. double URL encoded version of `newline`.
You may use the following CODE for filtering (in a plugin or in your active theme's `functions.php` file):
add_filter( 'clean_url', 'double_encoded_nl_to_encoded_nl' );
function double_encoded_nl_to_encoded_nl( $url ) {
return str_ireplace( '%250A', '%0A', $url );
}
Now, this: `esc_url( " );` will return ` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "urls"
} |
How to check in timber if user is loggedin?
How to check if there is a user is loggedin? Normaly you do this like:
`if ( is_user_logged_in() ) { // do something }`
but how you do this within a Timber template? some thing like?:
`{% if userloggedin %} //do somthing {% endif %}` | Found it already, to do this you can use the 'user' object:
` {% if user %} Hello {{ user.user_nicename }} {% else %} you are not loggedin {% endif %}` | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 6,
"tags": "login"
} |
Customizer - Prefix Class Extension
I have a basic question to beautiful working code I've found (paulund) for making a Custom Control by extending the 'WP_Customize_Control' Class. I am new to PHP, Programming and especially to OOP. So I wonder especially, what the first "condition" do, while the rest seems comprehensibly to me. I have a understanding problem with:
if ( ! class_exists( 'WP_Customize_Control' ) )
return NULL;
Read the php manual for "class_exists" and I read in a german blog, that the code above ensures, that we have no conflicts with other Plugins... .
I this is the idea of it, how does it work? Shouldn't the Class exist by Wordpress Core anyway? Sorry for my English. Many thanks in advance. | This is a terrible way to make sure you are in the right context. The normal way is to load your class only when it is really needed, not earlier.
A side effect is that the following code cannot be cached, because that line is evaluated on _run time_ , not on _compile time_. The same applies to `function_exists()`.
Summary: Don't do that. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php, theme customizer, theme options, oop"
} |
How to edit the default database of WordPress
How do I create a complete organisation's database, where I can access tables and perform custom SQL requests. I can use PHP and mySQL, I am actually working on a WordPress theme. And I am trying to do something like this:
+----------+ +------------+ +------------+
| Book | | Borrow | | Reader |
|----------| |------------| |------------|
|codeBook# |_____|codeBook# | |codeReader# |
|title | |codeReader# |_____|name |
|datepub | |date | |age |
+----------+ +------------+ |contacts |
+------------+
Some explanation and link will be great | You can do that accessing the phpmyadmin dashboard of your host, but that is no the right way to do it, i recommend you to research and learn about:
* Custom Post Types
* Custom Taxonomies | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -1,
"tags": "php, plugin development, theme development, database, mysql"
} |
How to link to a custom .php page in my folder
I have created a custom page that I have called mypage.php.
It is in my template folder with al the other pages (index.php, page.php, ...)
I want this page to be opened when i click on the below code.
<a href="<?php site_url(); ?>/mypage.php">Go to page</a>
When I click on the link the url in my browser look like: < which I guess is correct.
BUT it uses index.php as template ignoring the code I have into mypage.php
So all i am getting at the moment is an empty page with only my header and footer.
Is it possible to use pages in this way with Wordpress? I had a look online and on this site but I haven't been able to find a solution for this problem. | WordPress doesn't load templates that way.
# First: give the template a name:
To load a page template, first you'll have to make sure your template has a name. To do that, you'll have to have the following CODE in your template file (here `mypage.php`):
<?php
/**
* Template Name: My Page
*/
Once you have the above PHP comment, WordPress will recognise it as a template file.
# Then, assign the template to a page:
Now you'll have to create a WordPress `page` (from `wp-admin`).
While you create the `page`, WordPress will give you the option to choose a custom template (if there is one). After you choose the template and `Publish`, that page will use your `mypage.php` file as a template.

instead of creating the the search form by html forms and wp_query? | The big advantage is that it is easy! `get_search_form()` is only including the file searchform.php of the template. Most of the time it's not more as an simple input field. When the form is submitted search.php is loaded for displaying the found content.
It is possible to modify the search query using an pre_get_post action on the search. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "wp query, customization, search"
} |
Possible to configure nginx to ignore cache for logged in users in certain roles only?
I have nginx caching setup that ignores logged in users, but I have a lot of users in subscriber roles who SHOULD be served a mostly cached site. Is there a way to only ignore caching for SOME roles (like contributor and above) while leaving caching on for subscribers (and potentially other roles at some point)? | Here is what I ended up doing:
// Set disable cache for certain roles
add_action('init', 'add_custom_cookie_admin');
function add_custom_cookie_admin() {
if ( is_user_logged_in() ) {
$current_user = wp_get_current_user();
$thisrole = $current_user->roles[0];
if($thisrole !== 'subscriber') {
setcookie("disable_cache", $current_user->user_login, time()+43200, COOKIEPATH, COOKIE_DOMAIN);
}
}
}
// and then remove the cookie on logout
function clear_custom_cookie_on_logout() {
unset($_COOKIE["disable_cache"]);
setcookie( "disable_cache", '', time() - ( 15 * 60 ) );
}
add_action('wp_logout', 'clear_custom_cookie_on_logout');
And then I added this to my nginx cache:
if ($http_cookie ~* "disable_cache") {
set $skip_cache 1;
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "cache, nginx"
} |
Get "Image CSS Class" value from the Advanced Options section
By default, WordPress allows to add an extra class to the image via Advanced Options section: <
If I know the image (attachment) ID then how can I get this value?
I tried **get_post_meta** function but it did not show me that extra class. So, I am assuming I need to use an another function to retrieve the value. | The `Advanced Options` section you are talking about the one in the `Image Details`, the modal that shows when clicking here:
 {
echo("ciao4");
add_rewrite_rule('^DN1/', '/chi-siamo/', 'top');
}
add_action('init', 'custom_rewrite_basic1');
but when I load the link, I get the 404 page. | Theme's `functions.php` is not the best place to do these sort of URL rewrites.
> Why?: because in that case WordPress will be fully loaded and then redirected to a new link and then fully loaded again to show the page. That's a lot of delay for a page view.
Instead of that, you may use URL rewrite in `.htaccess` (assuming your web server is Apache):
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
# YOUR CUSTOM REDIRECT
RewriteRule ^DN1$ [L,R=301,NC]
# default WordPress rules
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "url rewriting, rewrite rules"
} |
Remove Customizer Control Choices (Type: Radio Array) using Child Themes
Is there a way to remove one of the choices from radio array? For example, I'm trying to remove 'bottom' from the choices' array:
$wp_customize->add_control(
'your_control_id',
array(
'label' => __( 'Control Label', 'mytheme' ),
'section' => 'your_section_id',
'description' => 'your_description,
'settings' => 'your_setting_id',
'type' => 'radio',
'choices' => array(
'top' => 'top',
'bottom' => 'bottom',
'left' => 'left',
'right' => 'right',
),
)
);
I know that the class below can modify nearly all the values from the control except the choices' array:
$wp_customize->get_control('your_control_id')->description = __( 'New Description' );
Any idea how to do this? | You can assign a `new array` there, with the updated options:
$wp_customize->get_control( 'your_control_id' )->choices = array( 'top' => 'top', 'bottom' => 'bottom' );
{
$wp_customize->get_control( 'your_control_id' )->choices = array( 'top' => 'top', 'bottom' => 'bottom' );
}
add_action( 'customize_register' , 'modify_choice',999 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "customization, theme customizer"
} |
Sidebar widgets are over the content in mobile mode, how can I fix it?
I'm building a website by modifying the Dazzling theme on WordPress, and I'm having a problem with the sidebar widgets (Text). Here's the link to the website: <
The website is working fine in full window, but when I try to restore the window down to a small size, or when I visualize it from a smartphone the sidebar gets over the main content.
Here's how it looks in resized window:  {
div#box {
overflow: hidden;
}
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "widgets, css, sidebar, mobile, responsive"
} |
Text Widget Links Not Working
I am trying to add a simple link to an 'About' page in a Sidebar Text Widget but when I test it the link does not work and I get an error on the linked page:
"The page cannot be displayed because an internal server error has occurred."
I know the link works because if I paste it directly into the browser the page comes up.
And I am pretty sure the html is correct for the link in the Text Widget:
<a href=” Site</a>
Any ideas?
The site Theme I am using is Avani - if that makes any difference.
Thanks | You are using the right double quotation mark `”` instead of the quotation mark `"`, use it like this:
<a href=" Site</a>
they look very similar but are different chars. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "widgets, html, links, widget text"
} |
Better action hook for creating table than after_switch_theme and switch_theme action hook
I want to create table only if my custom theme is activated. I have tried with `after_switch_theme` action hook but it is creating table regardless my custom theme. This means it is triggering action if I activate `Twenty fifteen` or any other theme.
add_action('after_switch_theme', ['\Recruitment\recruitment', 'create_table']);
I want to create table only if my custom theme is a current theme or activating that theme.
Is there any hook for it or any alternate way? | Ah I found it.
You can use `after_setup_theme` action hook. So it will be like
add_action('after_setup_theme', ['\Recruitment\recruitment', 'create_table']);
# Updated Code
$theme = wp_get_theme();
if ( $theme->name == 'My THEME NAME' ) {
global $wpdb;
global $charset_collate;
$sql = "CREATE TABLE IF NOT EXISTS ... $charset_collate;";
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
dbDelta( $sql );
add_option( 'ab_db_version', self::$db_version );
}
// in another file
add_action('after_switch_theme', ['\Recruitment\recruitment', 'create_table']); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "actions, table"
} |
Remove Close Button | Facebook Page Promoter Lightbox
Good day! I want to remove the close button in this plugin.
;
function corse_rewrite_rules( ) {
add_rewrite_rule('listings/make/([^/]*)/page/?([0-9]{1,})/?$', 'index.php?post_type=product&product_make_model=$matches[1]&paged=$matches[2]', 'top');
add_rewrite_rule('listings/make/([^/]*)/?$', 'index.php?post_type=product&product_make_model=$matches[1]', 'top');
}
Which should take a URL like this :
/product_make_model/stuff/
to :
/listings/make/stuff/
The issue in hand is that although the Rewrite is working and the new URL is accessible, its not redirecting the old URL to the new one.
If I also add an SEO plugin such as YOAST the canonical URL is listed as the the old URL confirming that there is something wrong.
Could someone shed some light as to what im doing wrong ? | Ok managed to figure this out, instead of adding action for a rewrite. Because what I was wanting to rewrite was a taxonomy i should have been using something like this :
'rewrite' => array('slug' => 'listings/make', 'product_make_model' => false)
When registering the taxonomy, which basically rewrites the slug as the taxomomy is created/registered.
Works perfectly. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "htaccess, rewrite rules"
} |
How to print the thumbnail only if a post has a thumbnail
I am using the following code to print another image that is in my images folder in casa a post has no thumbnail but it is giving me errors on the else statement saying that there is a syntax error:
<?php if ( has_post_thumbnail() ) {
echo '<a href="<?php the_permalink(); ?>"> <figure><?php the_post_thumbnail(); ?></figure></a>';
}
else {
echo '<figure><img src="<?php echo get_bloginfo( 'template_directory' ); ?>/images/stone.jpg" /></figure></a>';
}
?>
However, if I paste this code:
<?php if ( has_post_thumbnail() ) {
echo '<a href="<?php the_permalink(); ?>"> <figure><?php the_post_thumbnail(); ?></figure></a>';
}
else{
}
?>
It gives no error but also it does not display the thumbnail
Hope you can help | Try this inside else condition where no image assigned.
if (has_post_thumbnail()) {
?><a href="<?php the_post_thumbnail_url(); ?>">
<?php the_post_thumbnail();?>
</a><?php
} else {
echo '<figure><a href="add_link_here"><img src="'.get_bloginfo("stylesheet_directory").'/images/stone.jpg" /></figure></a>';
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "post thumbnails"
} |
Changing permalinks structure without loosing SEO
Current structure is `/%year%/%monthnum%/%postname%.html`
Desired structure is `/%postname%/`
Since we are already positioned with urls like `domain.com/2015/04/example-post.html`, we want people to be redirected to `domain.com/example-post/`.
I already tried installing some plugins, like **Simple 301 Redirects** , which looked good since it seems to work with rules as shown in the image below:
\.html$ /$1 [R=301,L]
Where
* `[0-9]+/` is the numeric year and month
* `(.*)` is the part we'll use below (`example-post` in your case)
* `/$1` is the part we've got from the above
301 redirect is completely perfect for SEO. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "permalinks, seo"
} |
Restrict partially matching usernames
I've been looking and looking for a solution for my problem but i have been unable to find anything.
I have found a plugin that allow me to restrict certain usernames, I found even a function but there is nothing that allows me to restrict partially matching usernames, there is nothing to prevent users to register under names like "joeadmin" or "seanadmin" and etc.
Is there anything that can be done to prevent users to register anything that contain "admin" and other prohibited words? | There's a `validate_username` filter hook that is used by `validate_user()` which is in turn used by `register_new_user()`.
So you can disallow usernames containing `admin` or other prohibited terms:
add_filter( 'validate_username', 'wpse257667_check_username', 10, 2 );
function wpse257667_check_username( $valid, $username ) {
// This array can grow as large as needed.
$disallowed = array( 'admin', 'other_disallowed_string' );
foreach( $disallowed as $string ) {
// If any disallowed string is in the username,
// mark $valid as false.
if ( $valid && false !== strpos( $username, $string ) ) {
$valid = false;
}
}
return $valid;
}
You can add this code to your theme's `functions.php` file or (preferably) make it a plugin.
## References
* `validate_username` filter hook
* `validate_user()`
* `register_new_user()`
* Writing a plugin | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "user registration"
} |
How can I include a query string with get_permalink
My login link uses `wp_login_url( get_permalink() )` so that the user is redirected back to the page they were viewing, and not to the dashboard.
However, this does not include query strings. So if a user was at `here.com/?page=4` they would not be redirected back to page 4.
How can I include the query string in my code?
$items .= "<li class='menu-item'> <a href=\"".wp_login_url( get_permalink() )."\">Login</a></li>"; | You can use add_query_arg() to add any query parameters you want to a URI, e.g.,
$redirect_uri = add_query_arg ('page', '4', get_permalink ()) ;
$login_uri = wp_login_url ($redirect_uri) ;
Or, you could simply use `$_SERVER['REQUEST_URI']`, which will already contain any query string present in the current page's URI, e.g.,
$login_uri = wp_login_url ($_SERVER['REQUEST_URI']) ; | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 3,
"tags": "permalinks, redirect, login, query string"
} |
Is it possible to restrict viewing of category PAGE to logged in users only?
I want to block the category page so that only logged in users can view the category page. I'm not talking about the posts in the page, I'm meaning the actual page view.
For instance, if I have a post category called "support", anyone can type in "/category/support/" after the domain name and view the posts in that category, but I need to restrict it so that only logged in users can see view that category page.
How can this be done? I don't need log in forms or anything special, just to block viewing of the category pages. I've tried adding custom meta keys into the category template that link with the wp-members plugin I've installed, and tried some other solutions including this one.
I can't find any plugins to do this, and no other code I've tried has worked yet. If anyone can help, that would be much appreciated! | There are plenty answers on WPSE about restricting page views based on logged in users or visitors.
what you should do is first check if user is logged in then check if you are on your _restricted_ category and redirect on another page (maybe home or login page) if user is not logged in.
something like this in your `functions.php` file.
add_action( 'template_redirect', 'wpse_restrict_support');
function wpse_restrict_support(){
if( ! is_user_logged_in() && is_category( 'support' ) ) {
wp_redirect( '/wp-login.php' );
exit;
}
}
check out is_category(), is_user_logged_in() and wp_redirect() for more info | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "categories, pages, content restriction"
} |
Jump links to another page and return back to the first page anchors successfully
I have made a one page website with their jump links using id attribute (#). These jump links are provided in the navigation bar (header navigation menu).
Now, we want to add another page, but the problem is that when we are on this new page, the anchors (jump links) of the first page don't work. The only solution is to click the home URL to return to the first page of the website.Is there any other solution? | You can use it like this < from another page. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "menus"
} |
Output category list inside array
I need to output information about each of my post categories in this array, but I'm having trouble figuring out how.
I need to output each category as an array (See examples) under the `values` option with the following information;
`'label' => 'CATEGORY NAME'` `'values' => 'CATEGORY ID'`
array(
'param_name' => 'ids',
'settings' => array(
'multiple' => true,
'values' => array(
// EXAMPLE
array( 'label' => 'Abrams', 'value' => 1, 'group' => 'category' ),
// EXAMPLE
array( 'label' => 'Brama', 'value' => 2, 'group' => 'category' )
),
),
),
I've tried using a `foreach` `get_categories()` loop inside the array but apparently PHP doesn't like that.
Any help would be greatly appreciated. | Try something like the following. Notice that the hide_empty argument is set to false.
$args = array(
'orderby' => 'id',
'hide_empty'=> false,
);
$cats = get_categories($args);
foreach ($cats as $cat) {
// Your code to populate new array here
}
And then assign your newly created array to values. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, array, categories"
} |
Dynamic name of cron event
In my multisite install, I'd like to add a daily cron event for some of the subsites. The cron will import posts via API from another website.
Because importing the content for all sites at once would end in timeout, I'd like to set a cron for each of the subsites.
In my class I did:
$cron_name = 'import_blog_posts_in_network_daily_'.get_current_blog_id();
if ( !wp_next_scheduled( $cron_name) ) {
wp_schedule_event( time(), 'daily', $cron_name );
}
add_action( $cron_name, array($this, 'import_blog_posts_in_network') );
That code registers the cron for each of my subsites correctly. But, I don't know, how can I access the name in my `import_blog_posts_in_network` callback
Is there a way to get the action name in the callback, to get the ID of my site? | So no, I can't see a way to grab the name of your action. However, you _can_ pass arguments to your callback:
$blog_id = get_current_blog_id();
$cron_name = 'import_blog_posts_in_network_daily_'.$blog_id;
if ( !wp_next_scheduled( $cron_name) ) {
wp_schedule_event( time(), 'daily', $cron_name, array($blog_id) );
}
add_action( $cron_name, array($this, 'import_blog_posts_in_network') );
/*
public function import_blog_posts_in_network($blog_id) {
// do something for blog $blog_id
}
*/
Hope that helps! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "actions, cron"
} |
API Rest Custom Post Type doesn't return all data
My friend has an site with WordPress 4.6.3, after Wordpress REST API vers 2 plugin was installed, added add_action() to function.php to enable API REST to custom post type.
With this < json contains only 10 data insted 71.
How can I fix it? Thanks! | By default WordPress return 10 posts per pages. To change the number of posts per page you should query ` The max is 100 posts per request. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom post types, rest api"
} |
how to get permalink using sql
I am trying to get post title by sql. My sql code is
$query ="SELECT wp_posts.post_title AS title ,
wp_posts.post_content AS content,
wp_posts.post_date AS blogdate
FROM wp_posts
WHERE wp_posts.post_status = 'publish'
ORDER BY wp_posts.post_date DESC ";
global $wpdb;
$result= $wpdb->get_results($query);
if ($result){
foreach($result as $post){
?><li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>">
<?php echo $post->title; ?></a></li><?php
}
}else{
echo "Sorry, No Post Found.";
}
die();
Now the problem is I am getting title but the_permalink() is not working. | I am not sure why you are using a custom query and not `get_posts()` or `WP_Query` as you should.
Anyway, you need to get the post ID …
$query ="SELECT wp_posts.post_title AS title ,
wp_posts.post_content AS content,
wp_posts.post_date AS blogdate ,
wp_posts.ID AS ID
And then just pass this ID to `get_permalink()`:
get_permalink( $post->ID );
Similar for the title attribute:
the_title_attribute( [ 'post' => $post->ID ] ); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "posts, permalinks, sql"
} |
Skip file when plugin updated
Is there a way to keep a constant file in my plugin directory so that it doesn't get updated? I'm a developer and would like to have a file for users to add custom functions to in my plugin. When they update the plugin, that file should not be updated if it already exists. Is this possible? | On you future code files in your plugin, do not include the 'option' file in the repository. Since it is not included in the repository zip, the file (if it exists) will not be overwritten on the user's system.
You may need some code in your plugin to create the file on activation with some default values, if it does not exist. That will ensure that the file will be there for the end user.
Although I am not a fan of letting users create files in the plugin area. It would be better, I think, to create an options page in your plugin that would contain the values (constants?) needed by your plugin. And your plugin would probably need to create those constants if they do not exist. (Remember that constants are 'constant', and cannot be redefined.) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "plugins, updates"
} |
Redirecting all posts after changing URL structure with htaccess
I am looking for the `.htaccess` regular expression that would redirect the old structure to the new one, the reason i don't want to use plugins is they often have unexpected results when WordPress updates or the author abandon them, I need something that would 301 redirect for a long time reliably.
Old permalink:
New Permalink:
**Note:** I am not sure if the rule should consider this but. I also use custom post types which add their slug to the url. So The "category" shows up for normal "post" but on CPT it's just:
I suspect a good rule could work for both cases since /%category%/ and /%example-cpt-slug%/ are _something between_ "/ /".
What I'm not so sure is how can you specify the POST ID (%post_id%/) as a target. | Within Settings > Permalinks your Custom Structure was set to `/%category%/%postname%/` right?
Now you want to set (or you've already set) to `/%post_id%/` right?
As far as I know (and I've also tested) WordPress will 301 redirect all of your posts (from the post type 'post') to your new Custom Structure. You won't need to do a thing.
So if you've set the Custom Structure to `/%post_id%/` it means that if someone accesses the URL ` they would be redirected to `
After you've changed your Custom Structure even if you also change your post slug WordPress will still redirect it correctly.
I don't know from which WP version this is supposed to work, but just for the record, I've tested within 4.7.
If it's not working for you let me know and I'll give you another solution.
By the way, I'm supposing your WordPress site URL didn't change as in your question you just used _domain.com_. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "permalinks, redirect, htaccess"
} |
Customizer: widget-synced triggers twice
I just noticed that `widget-synced` is triggered twice when you're trying to edit a widget, click on a text field, write something, triggers `widget-synced` once and after that, if you click anywhere else it triggers a second time.
 {
global $wpdb;
$domains = $wpdb->get_col( "SELECT active FROM $wpdb->dmtable} WHERE blog_id = %d", $blog_id );
// Do Something
}
}
add_action( 'wp_head', 'is_domain_mapped', -1); | Note that you should be able to map domains without 3rd party plugins.
Here's an untested suggestion for your callback in your current situation:
global $wpdb;
// Nothing to do if not multisite
if( ! is_multisite() )
return;
// Define the custom table
$wpdb->dmtable = $wpdb->base_prefix . 'domain_mapping';
// Check if the custom table exists
if ( $wpdb->dmtable != $wpdb->get_var( "SHOW TABLES LIKE '{$wpdb->dmtable}'" ) )
return;
// Check if current site is mapped
$domain_exists = (bool) $wpdb->get_var(
$wpdb->prepare(
"SELECT COUNT(blog_id)
FROM {$wpdb->dmtable}
WHERE blog_id = %d AND active = 1 LIMIT 0,1",
get_current_blog_id()
)
);
if( $domain_exists )
{
// do something
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "multisite, wpdb, domain mapping"
} |
How do I fit WP_Query arguments into a function?
How do I add this...
'date_query' => array(
'relation' => 'OR',
array(
'column' => 'post_date',
'after' => '-7 days'
),
array(
'column' => 'post_modified',
'after' => '-7 days'
)
)
into this...
//order home posts by modified
function order_home_asc($query) {
if ($query->is_home() && $query->is_main_query() && !is_admin()) {
$query->set('orderby', 'modified');
$query->set('order', 'DESC');
$query->set( 'post__not_in', array( 889, 738, 1008, 808, 638) );
$query->set('post_status', 'future,publish');
}
}
add_action('pre_get_posts', 'order_home_asc'); | This should work:
$query->set( 'date_query', array(
'relation' => 'OR',
array(
'column' => 'post_date',
'after' => '-7 days'
),
array(
'column' => 'post_modified',
'after' => '-7 days'
)
) );
You might want to adjust the callback's name, since it's not only ordering the home page. You also have `_asc` in that name but are setting the order to DESC within it. So it might cause confusion.
Note that you will not have accessible permalinks for the future posts.
It might be more flexible to filter the posts on the home page according to some category/tag/custom-taxonomy instead of excluding hardcoded post IDs. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query, functions"
} |
My CPT won't display no matter what I do
I create CPT and add new post. I can see that post in the Recent Posts but when follow the URL to that post, it only display the message "OOPS! THAT PAGE CAN’T BE FOUND."
I try to follow the instruction on many site and still can't solve this problem. I've already create single-{post-type}.php and the loop too but nothing change.
I use the Instant Wordpress 4.5 for local host and create a child theme from TwentySevenTeen, is it somehow caused this issue?
Please help me with this case, I try anything from yesterday and feel completely lost. Thanks very much for any help. | You need to flush rewrite rules after creating CPT, go to **Settings --> Permalinks** and save them. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom post types"
} |
How to automatically apply woocommerce product title to all product images alt tags?
Adding alt tag information to every product photo is a lot of work. We always just copy and paste our product title into the image alt tags.
I figured since all the information is there; there must be a way to do this automatically.
**Question:** How do you apply a woocommerce product's TITLE as all the ALT TAGS for images used with that product.
Any help is much appreciated! | This is what you need, taken from - <
add_filter('wp_get_attachment_image_attributes', 'change_attachement_image_attributes', 20, 2);
function change_attachement_image_attributes( $attr, $attachment ){
// Get post parent
$parent = get_post_field( 'post_parent', $attachment);
// Get post type to check if it's product
$type = get_post_field( 'post_type', $parent);
if( $type != 'product' ){
return $attr;
}
/// Get title
$title = get_post_field( 'post_title', $parent);
$attr['alt'] = $title;
$attr['title'] = $title;
return $attr;
} | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 4,
"tags": "php, functions, custom field, woocommerce offtopic, tags"
} |
How do I echo all of my taxonomies?
I'm trying to echo **all** of my custom taxonomies, but this only prints out the first one:
$skill_list = wp_get_post_terms($post->ID, 'skill', array('fields' => 'names'));
echo 'skill-' . $term->slug;
Does anyone have an idea of what I've done wrong? | Function wp_get_post_terms returns _array_ (or WP_Error but we ommit it here) so you need go through the returned array and print all items:
$skill_list = wp_get_post_terms($post->ID, 'skill', array('fields' => 'names'));
print_r( $skill_list );
Of course you can also yous `for` or `foreach` for better printing... | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "taxonomy"
} |
get_query_var returns wrong default value
I want to make my custom terms to be sortable by users. I've created different links to let the user decide how they want to sort it.
<a href="?orderby=name&order=asc" data-target="#">Name ascending</a>
<a href="?orderby=name&order=desc" data-target="#">Name descending</a>
<?php
$orderby = get_query_var('orderby', 'name');
$order = get_query_var('order', 'ASC');
echo $orderby . " : " . $order;
$args = [
'number' => $tpp, // Amount of terms to return
'offset' => $offset, // The amount to offset the list by for pagination
'orderby' => $orderby,
'order' => $order
];
$actors = get_terms( 'myTaxonomy', $args );
It works properly if the query vars are set. But if no query var is provided, I always get `DESC`.
As the default value for `$order` although I defined `ASC` as default.
What am I missing? | The default value of `get_query_var( $var, $default )` is only returned if the query variable `$var` isn't available in the global `$wp_query` object.
The `order` query variable actually falls back to the `DESC` value here:
if ( ! isset( $q['order'] ) ) {
$q['order'] = $rand ? '' : 'DESC';
} ...
within `WP_Query::get_posts()`, so that's why it's used instead of your default value.
Be careful when applying native public query variables, to secondary queries, because they can also change the main query result. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "order, query variable"
} |
get post meta before it is updated (during SAVE_POST)
Lets say I have custom field on post editor, and I change value from **AAA** to **ZZZ**.. :
add_action('save_post',
function($post){
$value = get_post_meta($post->ID, 'mykey');
}
, 1);
How to get the old value ( **AAA** ) of that meta-key? during save_post (even earlier 1st priority), I get **ZZZ** | > `save_post` Runs whenever a post or page is created or updated, which could be from an import, post/page edit form, xmlrpc, or post by email. Action function arguments: post ID and post object. Runs after the data is saved to the database.
above paragraph is quoted from WP Codex.
so you cannot use this hook to get older value because it fires after saving new values to DB. WP has another action hook named `wp_insert_post`but sadly this hook does same thing as `save_post`
alternatively you can use Filters to get the job done. WP provides few filter to edit the post while saving or before saving to DB. like `wp_insert_post_data` & `content_save_pre` might work for you, i think.
**Update**
here is another discussionon this topic which might be helpful for you. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 4,
"tags": "save post"
} |
admin_post equivalent for guest user?
I managed to create a view which submits data from a form to my plugin via `admin_post_*` action.
This is what I have:
class MyPluginClass {
public function __construct() {
add_action('admin_post_formsbmt', array($this, 'formSubmit'));
}
public function formSubmit() {
// handle the post here
}
}
Then, in the form:
<form method="post" action="<?=admin_url('admin-post.php')?>">
<input type="hidden" name="action" value="formsbmt">
[other inputs]
</form>
It works, but this way the user must be an admin to perform the POST request.
Is there an equivalent for guest user? I need to put this form on a public page so that anyone can submit forms.
Is that possible? | If you look at admin-post.php, there is a check for `wp_validate_auth_cookie()` not whether the user is an administrator. So anyone with a valid authorization cookie will trigger the `"admin_post_{$action}"` hook.
If the user doesn't have a valid authorization cookie, then WP will trigger `"admin_post_nopriv_{$action}"`. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "plugin development, forms"
} |
How is the single category page called and how does it know which posts to show?
I downloaded a blank theme and it has a category.php file that's not referenced anywhere in the code, but still appears when I try to view a single category. It also has a main loop that somehow always shows the correct posts without anything being declared anywhere. Is this just a wordpress thing? Is yes, is there some list of all files that will just work when placed in a theme, so I can delete the the ones exclusive to the not-so-blank theme? | Have a look at the following documentation, this should clear things up for you. Your list of files that make up a theme are explained here also. Including which files are used when.
< | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "categories"
} |
Woocommerce reviews xss issue
I enabled reviews on my woocommerce website and I see that I can insert html / js code in the review comments.
How can I solve that problem? | Go ahead and disable WooCommerce and comment on a post; you can do the same thing because you're logged in as admin. Admin users are able to post unfiltered content. If you repeat the test logged out, you'll notice you're not able to exploit anything.
See this trac ticket from WordPress <
And this article on make.wordpress <
For future reference, please report security issues responsibly rather than publicly - use < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "woocommerce offtopic, security, review"
} |
esc_attr() right way and use
First of all I want to tell that I am new in wordpress not very new but 2 months. My question are :-
1. Is it right to use esc_attr()
2. and the right way as I am using is it right or not
function dr_enable_and_disable_header() {
$options = get_option( 'custom_header' );
$checked = ( isset($options) && $options == 1 ? 'checked' : '');
echo '<lable><input type="' . esc_attr('checkbox') . '" id="' . esc_attr('custom_header') . '" name="' . esc_attr('custom_header') . '" value="' . esc_attr('1') . '" '. $checked .'> Activate Custom Header</lable>';
} | No you don't need `esc_attr()` function to print out fixed static text.
You only need it to print out dynamic or generated text, so that if the attributes have any special characters that may break your HTML, `esc_attr` will escape that properly.
In your particular case, you can just write:
echo '<label><input type="checkbox" id="custom_header" name="custom_header" value="1" '. $checked .'> Activate Custom Header</label>';
However, if you had any generated or user input text, then you should've used `esc_attr()`. For example:
$style = "__Some generated text from database or user input__";
echo '<label><input type="checkbox" id="custom_header" name="custom_header" value="1" '. $checked .' style="' . esc_attr($style) . '"> Activate Custom Header</label>'; | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 8,
"tags": "php, themes, security"
} |
php syntax - how to concatenate properly - echo bloginfo('stylesheet_directory)
This is driving me batty. Is my syntax wrong? Why is the first "." in my img src call throwing out an error? This works if I put a hard link in the img src call, FYI.
<a class="blog-image" href="<?php the_permalink(); ?>">
<?php if (has_post_thumbnail() ) {
the_post_thumbnail('medium-size');
} else {
echo '<img src="' . bloginfo('stylesheet_directory'); . '/img/ogpimage.png" alt="Blog Posts Placeholder">';
} ?>
</a> | 1. `bloginfo()` does already an `echo`. It will be printed before everything else in your `echo` statement. Use `get_bloginfo()` instead.
2. `stylesheet_directory` is one of these arguments where it is better just to use the function that is called by WordPress: `get_stylesheet_directory_uri()`. It is easier to understand, especially in this case where one could expect a path by looking at the name of the argument string.
3. If you are using an URL provided by a WordPress function, **escape it**. Always.
4. For better readability, I would use `printf()` here.
Summary
printf(
'<img src="%s/img/ogpimage.png" alt="Blog Posts Placeholder">',
esc_url( get_stylesheet_directory_uri() )
); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "php, css, bloginfo"
} |
What is the most idiomatic way to let clients edit phrases in HTML?
I added HTML banners to the top of certain pages on a client's site. He wants to make edits to the text phrases on these banners without having to edit any HTML. How do I open this up for him?
* * *
In the past, I have simply made a collection of pages that I insert into my HTML banners using the following code:
<div class="banner-top">
<h1><?php echo $about_us_phrase->post_title; ?></h1>
<p><?php echo apply_filters( 'the_content', $about_us_phrase->post_content ); ?></p>
</div>
But this feels hackish, especially because it forces the client to swim through a potentially large number of pages to find the one that corresponds to the text they'd like to edit.
What is the most Wordpress-y way to do this? | Are the banners related to each page? If so, I would use a custom field or just a metabox that the user could edit or enter information into on the page that you want the banner to show up. The field would show up below the content in the page editor. You would then in your single.php add the code you noted above to encase whatever is typed in the custom field.
If the banners are NOT related to individual pages. I would make a custom post type "banners" and then have them randomly show up on pages by inserting a call for the CPT within the single.php.
You can either use a plugin to create the fields or these reference links will help you get started on creating your own:
< (explanation etc)
< (code examples and usage) | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "customization, pages, html"
} |
Exclude current post for custom post type
What I need: show random post except current post for custom post type `Question`
In below codes, the exclusion doesn't works. It simply show any post including current post.
<?php
$my_query = new WP_Query( array('showposts' => '8', 'post_type' => 'question', 'post__not_in' => array( $post->ID ), 'orderby' => 'rand'));
while ( $my_query->have_posts() ) : $my_query->the_post(); ?>
<a href="<?php the_permalink(); ?>"><?php the_title() ?></a><br>
<?php endwhile; ?>
If I change the `Question` to be `Page`, it works for Page. If remove the `Question`, it works for Post.
I guess it must be something I missed if I want to make it works for custom post type
**Update:**
Previously I wrote `Question` now changed to `question`, but still results the same | You should use `get_queried_object()` or `get_queried_object_id()` to get the current custom post's ID. IMO `get_queried_object()` is a better choice here as you can conditionaly check for the post type also. Try this
function wpse258217_random_posts() {
$obj = get_queried_object();
if ( $obj->post_type === 'question' ) {
$postid = $obj->ID;
$my_query = new WP_Query( array('showposts' => '8', 'post_type' => 'question', 'post__not_in' => array( $postid ), 'orderby' => 'rand'));
//Execute the loop here
}
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types"
} |
Where are Additional CSS files stored
` that uses `wp_get_custom_css_post()`
and displayed through the `wp_head` action with:
* `wp_custom_css_cb()` | stackexchange-wordpress | {
"answer_score": 38,
"question_score": 29,
"tags": "customization, themes, css"
} |
301 redirect via htaccess rules on the new site
Old site: abc.com New site: abc.org
The old site, abc.com, is only a "parked site" now, so there is no .htaccess files any more for that domain name.
So all htaccess rules need to be in the .htaccess file on the new domain name, abc.org.
Can someone please help me with the rules so that all .COM urls gets forwarded to the .URL equivalent URL...??
So for example, if someone goes to abc.com/dir1/dir2/aboutus.php then they will be redirected to the same URL but on the new domain, abc.org/dir1/dir2/aboutus.php
Thanks in advance. | What you want to do is Domain Name Forwarding, and it CAN NOT be done using .htaccess of the target domain. If you are using godaddy to register your domain, here is a guide that they have prepared for people who would want to forward one domain to another:
<
The process is about the same for other domain name registrars. You have 2 options when doing the domain forwarding. One is to keep showing the original domain, such as abc.com in your example. This is Forwarding with Masking. The other option is to forward abc.com to abc.org and the user sees abc.org in the browser. This is Forwarding without Masking. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "redirect"
} |
Instructure Canvas API with Wordpress
My client has an account on Canvas LMS where he is running his institute, he wants a wordpress website that should be connected to his canvas LMS account and he should be able to handle requests from his website, like if a user, after logging in, changes something in his profile then it should changed in the main application (canvas LMS) too, he should be able to edit courses, view courses etc on his website. I am not sure from where to start this, I have searched the internet but couldn't find anything relating Canvas LMS API with worpdress. If someone can point me in the direction from where to start that would be a huge favor. I am new to APIs with wordpress and dont know how to authenticate or get access token and then how to send requests to the API using wordpress.
Thanks in advance | Generally speaking, you will need to create a plugin to accomplish the connection and manipulate data. It looks like Canvas uses JSON in their API. There is a good overview of handling JSON in PHP \- the rest you will probably need to piece together from Canvas's API documentation. Before you get started, make sure both sites are running over HTTPS so you don't expose any sensitive information.
Since there are no Canvas-to-WordPress-specific tutorials available, you might also find it helpful to go through Google's OAuth 2.0 tutorial for practice in connecting using OAuth, and then work on connecting to Canvas. In my experience connecting is the hardest part. From there, piecing together requests becomes easier.
Out of curiosity, why is the client asking you to build a WordPress site that manipulates Canvas data? I work in higher ed and would love to hear more about their use case. Are they trying to provide a different front end for faculty? | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "api, customization"
} |
Use .php file as page instead of wordpress page & template file?
Im trying to find a tutorial for this but i can't seem to find one, and im just newbie in wordpress.
Is it possible to use certain php file as page on a wordpress site instead of the regular wordpress page using template file so i dont have to create a page for each?
I mean for example, i'd like to create a Control Panel page: i'll use: usercp.php anywhere in my theme folder and i'll be able to open it on my site like: site.com/usercp/
If it's possible, maybe you could send me some links on where i could read and understand how it works.
Thanks! | Yes you can do this but creating template like usercp.php .
(1) First create usercp.php template and then this one line at first of template.
update_post_meta(get_the_ID(), 'usercp', 111);
(2) Then create page and assign template.
(2) Then go to your functions.php file and add this code
add_action('template_redirect', 'setPrivateTemplate');
function setPrivateTemplate()
{
if (get_post_meta(get_the_ID(), 'usercp', true) === 111) {
load_template(dirname(__FILE__) . '/your-folder-name-inside-theme/usercp.php');
exit();
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, functions, theme development, pages"
} |
Do I need to use jQuery for my template?
I know that jQuery is used as part of the WordPress core, and it comes as standard when creating a jQuery template.
I was wondering, however, if it is possible to avoid using jQuery as part of a template and use an alternative, D3, for instance? | Yes, the scripts you use are totally up to you. Keep in mind many plugins rely on common libraries like jQuery so even if you exclude it from the theme, some of your plugins may add it back in. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "jquery, core"
} |
Some images not appearing after switching from AWS S3 back to local
I'm using a plugin Amazon AWS for Wordpress.
It creates **a copy** of your images on S3 and also serves them from there while active.
When you deactivate it, it should just work locally.
AWS S3 is experiencing problems today so I turned off the plugin and to my surprise there are lot's of missing images.
What could be causing images to not be saved locally but work fine on S3?
_I'm also using a simple filenames plugin to make sure there are no special characters (some people are using Chinese, Cyrillic, etc.) that my local linux machine won't like._
Here's a page with lots of missing images: < | It looks like the problem is some of your images are redirected. When I inspect one of the missing images in Chrome, right-click on the background-image CSS and open it in a new tab, it is redirecting to the homepage. HTTP Header Check returns a 302 found, so somewhere these images are still set to redirect. Perhaps you have a caching plugin or a redirect plugin? I'd try deactivating all plugins and then turning them on one by one to identify what may be redirecting. You could also check .htaccess. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "uploads, urls"
} |
Where does Yoast SEO plugin sets the site/page title?
I am running on `WP 4.7.2` and `Yoast SEO 4.4`. I want to append a PHP variable to all titles. But it seems I am not able to do that.
I have read that `wp_title` used to be the method before WP 4.4, then it was removed, and then it was returned because of some 'bug'?
I have tried using the `wpseo`+`add_filter` method, but it does not set the site title.
I have searched `/wp-content/plugins/wordpress-seo` via `grep -r '<title>' *` and am not seeing where the plugin sets the title tag. It did return few lines, but none of them seem to be related.
I found the following code in `clss-frontend.php`:
// When using WP 4.4, just use the new hook.
add_filter( 'pre_get_document_title', array( $this, 'title' ), 15 );
add_filter( 'wp_title', array( $this, 'title' ), 15, 3 ); | There's a `wpseo_title` filter you can hook into. Example:
add_filter('wpseo_title', 'add_to_page_titles');
function add_to_page_titles($title) {
$title .= $addToTitle;
return $title;
} | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 0,
"tags": "title, plugin wp seo yoast, description, wp title"
} |
Assign a picture URL to a page via PHP
I would like to assign a picture URL via PHP to a page. I’ve googled already but just found something like this:
<
Does anyone have an idea how I can assign a picture URL to a page via PHP?
Furthermore the picture has to be integrated via the URL and not be downloaded in my media library and not be applied from there. So external.
What I mean is this here (Called Featured Image in English):
, 'my_custom_image_url', ' true );
The code above assumes that **a)** you will have only one image per page; and **b)** you are in a loop so `get_the_ID` will return a valid ID of the page you want to attach the meta-data to. Documentation here. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "php, images, post thumbnails"
} |
woocommerce_email_attachments filter arguments
I’m trying to generate PDF attachment for new order emails in WooCommerce and this is what I found:
add_filter('woocommerce_email_attachments', 'attach_terms_conditions_pdf_to_email');
function attach_terms_conditions_pdf_to_email($attachments, $type, $object) {
$your_pdf_path = get_template_directory() . '/file.pdf';
$attachments[] = $your_pdf_path;
return $attachments;
}
This works, but I need to dynamically generate PDFs based on order (should be in `$object->order`), however nothing but `$attachments` is passed to my callback function – `$type` and `$object` are always `null`. `func_get_args()` gives only empty `$attachments` array. | A mild stab in the dark, you aren't telling `add_filter` your accepted argument count. It's an important element. It does require you to also be explicit about the priority too.
add_filter( 'woocommerce_email_attachments',
'attach_terms_conditions_pdf_to_email', 10, 3 ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "woocommerce offtopic, attachments, email"
} |
Whats the template of my homepage?
So i'm new at wordpress, I want to add some php code in my home page, but I don't understand why neither page.php or front-page.php seems to act as a template to my homepage
I tried to copy front-page.php and I put
/**
* Template Name: homepagetemplate
**/
edited the html and add some super-big Text to see if it works....
Then set the template in wordpress and no big text I see.
Tried the same with page.php, but nothing seems to work, I even tried editing page.php and front-page.php directly and I see nothing
If I do the same with a page that is not my homepage it works if i edit page.php, but not for my homepage | Themes authors have different approaches and organize their files differently.
The fastest way to know which theme files were used to generate the current page is to use the plugin What the File, it adds a small section in the admin toolbar.
. My site is running the most recent version of WordPress (4.7.2).
When I tried to install it, it gave me some error having to do with files, and I can't find the error message anymore. Yoast ceased to be displayed as a plugin installed on the server (not listed under active or inactive either). I tried to re-install it, but it threw an error along the lines of
error: tried to create a directory that already exists
or something like that.
So, here's my question:
How do I uninstall Yoast when it doesn't show up as installed anymore? Is it safe to do so?(if I need to use FTP, what file path might I find it at?)
Thanks for any help! If I didn't provide enough information, please let me know what I need to give (I'm sort of new at WordPress) | If you just want to delete Yoast SEO manually so you need to login into your server and delete the following folder:
`.../wp-content/plugins/wordpress-seo`
So you will delete the directory `wordpress-seo`.
_If I were you I'd do it via SSH as Yoast SEO has approximately 600 files._ | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, errors, plugin wp seo yoast, uninstallation"
} |
Display correctly using metabox.io
I'm struggling to find the proper way to display the date at the front end of my theme. I am using metabox.io for custom fields in my custom post type.
The basic way to echo is this: echo rwmb_meta( 'ls_course-date-1'); ls_course-date-1 being my field id.
the documentation to display a pretty date is here but I don't know how I am meant to implement it. It refers to further documentation herebut again, I don't know how to implement. My php level is intermediate at best and whilst I've had no problem creating all of the arrays and returning most of them, I'm stuck here. | The answer was much simpler than I thought.
$date_meta = rwmb_meta( 'ls_course-date-3');
echo date('jS F, o ', strtotime($date_meta)); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom post types, metabox"
} |
Notice: wp_get_http is <strong>deprecated</strong> since version 4.4.0!
How can I fix this error:
Notice: wp_get_http is <strong>deprecated</strong> since version 4.4.0! Use WP_Http instead. in C:\...\wp-includes\functions.php on line 3828
I try to use Importer and get these error. | This is a known core issue, see e.g. this ticket. There is work done fixing this issue by a complete rewrite of the importer, but no ETA for it yet.
For now as this is only a Notice you can safely ignore it for the time being. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 4,
"tags": "plugins"
} |
Change "logged in" link in (you must be logged in to post a comment)
I need to change the link for "logged in" to a user log in url instead of wp login url. I have checked /wp-includes/comment-template.php and that's what I found on line 2217
/** This filter is documented in wp-includes/link-template.php */
'must_log_in' => '<p class="must-log-in">' . sprintf(
/* translators: %s: login URL */
__( 'You must be <a href="%s">logged in</a> to post a comment.' ),
wp_login_url( apply_filters( 'the_permalink', get_permalink( $post_id ) ) )
) . '</p>',
If this is the right place to customize the "logged in" link, how should be the code with a new login page url example: yourdomain.com/my-account ?? | To change the login link only in this template, replace the `wp_login_url()` function call with your login link:
'must_log_in' => '<p class="must-log-in">' . sprintf(
/* translators: %s: login URL */
__( 'You must be <a href="%s">logged in</a> to post a comment.' ),
"
) . '</p>',
If you want to generally redirect users to another url if they need to log in, it is better to use the filter `login_url`:
function wpse_258398_login_url ( $login_url, $redirect, $force_reauth ) {
return "
}
add_filter( 'login_url', 'wpse_258398_login_url', 10, 3);
Be aware though, this will affect all redirects to login. Even when you are redirected to login for the admin backend. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "customization, comments, login, comment form"
} |
How to automatically resize animated GIFs used as Featured Images, without losing animation?
I know that WodPress has support for embeding animated gif images on posts but I need the animated images to be used as featured images and to be shown on the post page as well as on all my post lists maintaining image resizing and animating.
I need to maintain a responsive size of it when i display it using a grid for homepage that use for example, a custom image sizes like 340x250px Curently the animated gif it not display correctly. Ant tips? | A gif should work as a featured image. Upload the gif as the featured image and display on the post page (single.php) for example, using the following for the original size:
the_post_thumbnail('full');
In the case of specific image sizes, i.e.
<?php the_post_thumbnail( 'custom-size' ); ?>
WP generates static images and in that case the gif wont work.
My suggestion would be to use conditionals to check if the attachment is a gif and use the full version in that case and rely on css to match.
$image_id = get_post_thumbnail_id($post->ID);
$type = get_post_mime_type( $image_id ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "post thumbnails"
} |
How do I add a php statement to a jQuery string
I want to insert a php statement into a jQuery String to update the user profile dynamically.
Here is my not working code so far:
jQueryVarWP("#kreis1").append("<option value=\""+array_list[i]+"\"<?php selected("+array_list[i]+", get_the_author_meta( \"kreis\", \$user->ID ) );?> >"+array_list[i]+"</option>");
My problem is somewhere here:
"<?php selected("+array_list[i]+", get_the_author_meta( \"kreis\", \$user->ID ) );?>
Maybe someone can help me to build this string. | You might want to try to use wp_localize_script() to allow your javascript to use data that are normally only available using php. Here is the link in the codex that will help you do what you need:
<
Another way is to use a php to output your entire javascript code (in a php file, that is, and not a js file). That way you can use php the way you would normally do. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, jquery, profiles, query string"
} |
Display Slug instead of Name
Im trying to display the slug instead of the name of on a product single meta. This is the code which is displaying the current category name with a link to the category. Id like to do the same but use the slug as instead :
<?php
global $post, $product;
$cat_count = sizeof( get_the_terms( $post->ID, 'product_cat' ) );
?>
<div class="product_meta">
<?php echo $product->get_categories( ', ', '<span class="posted_in">' . _n( 'Location:', 'Locations:', $cat_counts, 'woocommerce' ) . ' ', '</span>' ); ?>
<?php do_action( 'woocommerce_product_meta_end' ); ?>
</div>
Thank you | From your code, it looks like `product_cat` is a custom taxonomy. `get_the_terms` returns an array you can get the slug from. For instance...
$terms_array = get_the_terms($post->ID, 'procuct_cat');
$term_slug = $terms_array['your index']->slug; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "categories, taxonomy"
} |
I want to load in a new class but only if the current page is single-movies.php
I am trying to add an extra class to my div but only if the current page is being served up by my single-movies.php page.
The below code is what I was hoping would work but it doesn't.
<div class="sponsors <?php if(is_page('single-movies.php') { echo " movies" } ?>"> | You should probably have a look at `is_page_template()` which actually can check whether a specific template is used.
So your code should be like:
<div class="sponsors <?php if( is_page_template('single-movies.php') ) { echo " movies"; } ?>">
Be aware, that `is_page_template()` does not work within The Loop, as written in the Codex. You may have a look at the alternative which is mentioned there.
Edit: Added in a ; after " movies" | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "php, functions"
} |
How to search for posts given post_content AND post_excerpt using WP_Query?
Trying to search for posts given post_content AND post_excerpt. Here is my code:
$query = new WP_Query(array(
'post_type' => 'post_type_here',
'post_content' => $order_id,
'post_excerpt' => $product_id
));
echo "<pre>";
print_r($query->posts);
For some reason, this codes result is all of the posts in that post_type.
I need it to show the posts WHERE post_content = VALUE AND post_excerpt = VALUE. | The only solution I could find for this was to save my two values as post_meta, then use this code:
$args = array(
'post_type' => 'POST_TYPE_HERE',
'post_status' => 'active',
'update_post_term_cache' => false, // don't retrieve post terms
'meta_query' => array(
'relation' => 'and',
array(
'key' => 'META1_NAME',
'value' => $order_id,
'compare' => '=',
),
array(
'key' => 'META2_NAME',
'value' => $product_id,
'compare' => '=',
)
)
);
$posts_array = new WP_Query($args); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "wp query"
} |
file_exists() acting weird
I'm trying to pull some data out of a csv file but I'm stuck because `file_exists()` says the file doesn't exist when used with `get_template_directory_uri()`.
This is the short code:
function getPeopleNumber() {
$csv = get_template_directory_uri().'/report/report.csv';
$delimiter=',';
if(!file_exists($csv) || !is_readable($csv)) {
return FALSE;
}
$header = NULL;
$data = array();
if (($handle = fopen($csv, 'r')) !== FALSE) {
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
if(!$header) {
$header = $row;
}
else $data[] = array_combine($header, $row);
}
fclose($handle);
}
return $csv;
}
If I `echo $csv` there's the complete (and correct) path.
But still the function returns `FALSE`. What am I doing wrong? | You are using `get_template_directory_uri()`, that's URL, not PATH.
Instead use `get_template_directory()`, that'll return PATH. Like:
$csv = get_template_directory() . '/report/report.csv'; | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "php, csv"
} |
Adding a video description in a similar way to a image caption
I'm looking for a solution to add a short description to a embed video that will allow for it to be styled a bit like the one that is used for images.
The only option I have found is using JavaScript to find the paragraph after the image and add a class which is then styled. This obviously could result in human error depending on the content after the image. | It will be interesting to see how the new evolving WP Gutenberg editor will handle shortcodes and embeds.
* * *
If you use the `[embed]` shortcode for embedding, then a semi workaround, without UI support:
[embed src=" desc="some description"]
where the custom `desc` attribute is supported with with this kind of wrapper:
add_filter( 'embed_oembed_html', function( $return, $url, $attr )
{
if( ! isset( $attr['desc']))
return $return;
return sprintf(
'<div class="oembed-wrapper">%s<span>%s</span></div>',
$return,
esc_html( $attr['desc'] )
);
}, 10, 3 );
You would then need to adjust it further with some CSS.
ps: there are ways to add UI to shortcodes, like the Shortcake plugin. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "videos, captions, description"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.